【问题标题】:How to sort Firebase keys that were created with "push()"?如何对使用“push()”创建的 Firebase 键进行排序?
【发布时间】:2014-12-28 02:57:58
【问题描述】:

根据 Firebase 文档:

push() 生成的唯一名称带有前缀 客户端生成的时间戳,以便生成的列表将是 按时间顺序排列。

那么,当我从所有子节点均通过push 创建的节点中检索列表时,如何将此对象转换为按时间排序的数组?在 AngularFire 中,有 $asArray() 方法似乎可以为您执行此操作。如果没有 AngularFire,我怎么能做到这一点?

我正在尝试做的代码示例是:

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?
  */
})

在此 plunkr 中的 script.js 下:http://plnkr.co/edit/yEcBK7PVTf7VxjnVhNXL?p=info

【问题讨论】:

  • 如果您显示您的代码会有所帮助。但最有可能您正在寻找的是传递给on(child_ 事件的previousChild 参数。见firebase.com/docs/web/api/query/on.html
  • 假设我有一堆之前通过push() 推送到/parent 的对象。然后我通过以下方式检索这些对象:parentRef.once('value', function(snap){var children = snap.val()})children 对象将类似于{pushID: data, ...}。问题是如何将children 转换为被pushID 的时间年表缩短的数组
  • 当您检索单个值时,子项已经按其优先级(或者如果它们没有优先级,则它们的键)或您在orderByChild 中指定的任何内容进行排序。因此,如果您使用基本的push 添加和检索子代,它们将按时间顺序排列。
  • 这让我不清楚你在问什么。您能否编写一个代码+数据的最小示例来演示您要解决的问题(请参阅stackoverflow.com/help/mcve)?点击您问题下方的编辑链接以添加此信息。
  • 好的,我添加了一个 plunkr,希望能解释我想要做什么。如果我仍然不清楚,请告诉我。

标签: firebase angularfire


【解决方案1】:

如果您尝试将所有子项按其键的顺序放入一个数组中,您可以使用DataSnapshot's forEach method

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

forEach 之后,您的数组将以正确的顺序包含所有子项。

但请注意,每次添加/删除任何子项或修改任何现有子项时,都会触发此操作。如果你使用这个数组来构建一个 HTML DOM,你最终会每次都重新绘制整个集合。

这就是为什么 Firebase 还会为特定子级触发事件:child_addedchild_changedchild_removedchild_movedon 的签名定义为:

on() - on(eventType, callback, [cancelCallback], [context])

回调是一个函数,记录如下:

当指定事件发生时触发的回调。回调将传递一个 DataSnapshot。出于排序目的,“child_added”、“child_changed”和“child_moved”还将按优先级顺序传递包含前一个孩子的键的字符串(如果是第一个孩子,则为 null)。

因此,使用previousChild 参数,您还可以重建正确的顺序(您只需要自己做)。

有关更多信息,请参阅Firebase documentation on these events

【讨论】:

    猜你喜欢
    • 2021-06-23
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    相关资源
    最近更新 更多