How do I sort Firebase keys generated with "push ()"?

According to the Firebase docs:

The unique name generated by push () is prefixed with a client-generated timestamp so that the resulting list is chronologically sorted.

So how do I get a list from a node where all of its children are created using push

, how do I convert this object to a chronologically sorted array? AngularFire has a $ asArray () method that seems to do this for you. How can I do this without AngularFire?

The example code I'm 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

+3


source to share


1 answer


If you are trying to put all the children in an array in their key order, you can use the DataSnapshot methodforEach

ref.on('value', function(snap){
  var children = [];
  snap.forEach(function(child) {
    children.push(child.val());
  });
  console.log(children.length);

      

After that, forEach

your array will contain all the children in the correct order.

But keep in mind that this will fire every time any child is added / removed or any of the existing children is changed. If you use this array to create the HTML DOM, you will redraw the entire collection every time.

Therefore Firebase also launching events for individual 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 registered as:

A callback that fires when the specified event occurs. The callback will be passed to DataSnapshot. For ordering purposes "child_added", "child_changed" and "child_moved", a string containing the key of the previous child is also passed in order of precedence (or null if this is the first child).

So, with the parameter, previousChild

you can also restore the correct order (you just have to do it yourself).

For more information, see the Firebase documentation for these events .

+4


source







All Articles