Reputation: 345
I'm trying to get an array of items from my Firebase database, using a snapshot generated on page load. I've added the value of each object to an array, and now I'm trying to push an item from each object into another array with a for loop.
But when I create the second array, there are more items in it than there are objects in the snapshot.
I'm wondering how I can get around this. Any help would be awesome. Thanks.
Code:
var ref = firebase.database().ref().child('/scenes/' + projId).orderByChild('wordcount');
ref.once('value',function(snap) {
snap.forEach(function(item) {
var itemVal = item.val();
keys.push(itemVal);
for (i=0; i < keys.length; i++) {
counts.push(keys[i].wordcount);
}
});
});
Upvotes: 9
Views: 37561
Reputation: 1600
You can just use lodash _.toArray()
_.toArray(snapshot.val())
will convert your object into an array of objects.
Upvotes: 8
Reputation: 11
@mike axle: Just add return true inside forEach. It works for me... ;)
Upvotes: 1
Reputation: 28750
Each time you add something to keys you loop over them all again. You should probably move it outside your forEach:
var ref = firebase.database().ref().child('/scenes/' + projId).orderByChild('wordcount');
ref.once('value',function(snap) {
snap.forEach(function(item) {
var itemVal = item.val();
keys.push(itemVal);
});
for (i=0; i < keys.length; i++) {
counts.push(keys[i].wordcount);
}
});
Upvotes: 18