[英]How to get the last item from every firebase object and put it into an array
Folks I'm using React Native Firebase
and I want to achieve as you can see in the attached ss
伙计们,我正在使用
React Native Firebase
,我想实现如您在附加的ss
中看到的那样
there's message
key and it has threads underneath and each thread have multiple messages.I want to do like I want get last item from every thread and put it into an array.How to achieve.I'm trying to use foreach and not getting my desired result有
message
键,它下面有线程,每个线程都有多条消息。我想做的就像我想从每个线程中获取最后一项并将其放入数组中。如何实现。我正在尝试使用 foreach 而不是我的期望的结果
here is my code这是我的代码
messagesRef.on('value', snapshot => {
let messsagesFB = [];
snapshot.forEach(element => {
messsagesFB = [...messsagesFB, element.val()];
});
});
I know my code will push every element but i want to push only last item from each thread我知道我的代码会推送每个元素,但我只想推送每个线程的最后一项
For your database reference messagesRef
, try adding .orderByKey().limitToLast(1)
for the query, in which case a loop would not be needed.对于您的数据库参考
messagesRef
,尝试为查询添加.orderByKey().limitToLast(1)
,在这种情况下不需要循环。
messagesRef.orderByKey().limitToLast(1).on('value', snapshot => {
// TODO: Add to array
}
There's also always the catch for the last iteration of a jQuery foreach
loop. jQuery
foreach
循环的最后一次迭代也总是有问题。 In your case, you could simply do:在您的情况下,您可以简单地执行以下操作:
snapshot.forEach(function(element, idx, messagesFB) {
if (idx === messagesFB.length - 1){
messsagesFB.push(element.val());
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.