2
votes

I was having some troubles when trying to retrieve from Firebase. Basically my groups table as such:

In this case, under group ID -KpFibCHjJ1xpfLd07WJ, there is one account ID -KpFiX2L7ENt6EBgrB0S. By right there will be more than one account, I am still working on the data insert.

I tried to retrieve the list of unique push ID for accounts under certain group:

var accounts = [];
    var query = firebase.database().ref('groups').orderByChild('address').equalTo('Blk 165');
    query.once( 'value', data => {
        data.forEach(userSnapshot => {
            let groupData = userSnapshot.val();
            console.log(groupData );
            accounts.push(groupData .accounts);

            for(var i = 0; i < accounts.length; i++){
              console.log(accounts[i]);
            }
        });
    });

However, what has printed out from for loop is:

Object {
  "-KpFiX2L7ENt6EBgrB0S": true,
}

Any ideas on how to extract out the list of unique push ID (-KpFiX2L7ENt6EBgrB0S) under certain child and store them into a temporary array?

2

2 Answers

1
votes

The trick is to Object.keys(groupData.accounts):

var accounts = [];
var query = firebase.database().ref('groups').orderByChild('address').equalTo('Blk 165');
query.once( 'value', data => {
    data.forEach(userSnapshot => {
        let groupData = userSnapshot.val();

        let accounts = Object.keys(groupData.accounts);

        console.log(accounts);
    });
});
2
votes

I don't really use Firebase, but sounds like you are attempting to extract a specific key from an array of objects? You could do something like this to get you on the right path, but I am still unsure if this is what you are asking for.

I've created a dumby set of data to attempt to match what you are getting for results.

var arr = [
  { 
    "-KpFiX2L7ENt6EBgrB0S" : true 
  },
  { 
    "-MXDOFKFFM3738FJF" : true 
  }
]

// Will store the info you want
var arr2 = []

for(var i = 0; i < arr.length; i++) {
  var temp = Object.keys(arr[i]).toString()
  arr2.push(temp)
}

console.log(arr2) // ["-KpFiX2L7ENt6EBgrB0S", "-MXDOFKFFM3738FJF"]

Here's a working codepen as well.