简体   繁体   English

如何从每个 firebase object 中获取最后一项并将其放入数组中

[英]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 resultmessage键,它下面有线程,每个线程都有多条消息。我想做的就像我想从每个线程中获取最后一项并将其放入数组中。如何实现。我正在尝试使用 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.

相关问题 如何获取数组中每个项目的最后一个元素子元素 - How do I get the last element child for every item in an array 从对象数组中获取最后一个为对象的项目 - Get the last Item which is an object from an array of objects 如何获取数组的最后一项并在JavaScript中从数组中删除它? - How to get the last item of an array and delete it from the array in JavaScript? 如何从火力地堡中获取数据作为离子数组中的键数组3 - how to get data from firebase as array of key that array of item in ionic 3 如何获得数组中每个项目的最后一个元素子项,然后在单击它们时显示它们 - How do I get the last element child for every item in an array and then show them if they are clicked on 如何根据角度8中的条件从对象数组中获取最后一个对象 - How to get last object from array of object based on condition in angular 8 Firebase JavaScript - 数组中的映射值仅显示最后一项 - Firebase JavaScript - Mapping values from array only display last item 获取数组中的最后一项 - Get the last item in an array 如何从脏形式的 object 中获取值并将其放入数组中? - How to get values from object of dirty form and put into Array instead? 我怎样才能得到数组的最后一项? - How can i get the last item of array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM