According to the Firebase docs:
The unique name generated by push() is prefixed with a client-generated timestamp so that the resulting list will be chronologically-sorted.
So how when I retrieve a list from a node where all its children are created via push, how do I convert this object into a chronologically-sorted array? In AngularFire, there is the $asArray() method which seems to do this for you. How can I do this without AngularFire?
An code example of what I am trying to do is:
var ref = new Firebase('https://your.firebaseio.com/')
ref.on('value', function(snap){
var obj = snap.val()
console.log(obj)
/*
obj looks like: {-JeHAy0QO5jhCAecc-Ha: {name: "item 1"} ..}.
I'd like to loop through this collection in
chronology order, but in JS, one should not rely on the order that key values
come while using a for-in loop. So I figured that instead, I probably need
to transform it into an array first then use a regular for loop.
Therefore, I'd like to transform obj into an array:
[{name: 'item 1'}, {name: 'item 2'}, ..]
where the order of the array is chronologically ordered (ie somehow decode
and use the keys of obj to sort the object). How do I do this?
*/
})
under script.js in this plunkr: http://plnkr.co/edit/yEcBK7PVTf7VxjnVhNXL?p=info
If you're trying to put all children into an array in the order of their key, you can use the DataSnapshot's forEach method:
ref.on('value', function(snap){
var children = [];
snap.forEach(function(child) {
children.push(child.val());
});
console.log(children.length);
After the forEach your array will contain all children in the correct order.
But be aware that this will fire each time any child is added/removed or any of the existing children is modified. If you use this array to build a HTML DOM, you'll end up repainting the entire collection every time.
That's why Firebase also fires events for the specific children: child_added, child_changed, child_removed and child_moved. The signature for on is defined as:
on()-on(eventType, callback, [cancelCallback], [context])
And the callback is a function documented as:
A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot. For ordering purposes, "child_added", "child_changed", and "child_moved" will also be passed a string containing the key of the previous child, by priority order (or null if it is the first child).
So with the previousChild parameter you could then also reconstruct the correct order (you'd just have to do it yourself).
Fore more information see the Firebase documentation on these events.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With