【发布时间】: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