gpt4 book ai didi

firebase - 如何对使用 "push()"创建的 Firebase key 进行排序?

转载 作者:行者123 更新时间:2023-12-01 12:38:09 24 4
gpt4 key购买 nike

根据 Firebase 文档:

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

那么当我从一个节点中检索一个列表时,它的所有子节点都是通过 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

最佳答案

如果您尝试将所有子项按其键的顺序放入一个数组中,您可以使用 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 触发事件:child_addedchild_changedchild_removedchild_movedon 的签名定义为:

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

回调函数记录为:

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).

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

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

关于firebase - 如何对使用 "push()"创建的 Firebase key 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27673354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com