How to loop through the data I receive from snapshot.val() and push it to an array based on keys(如何遍历从 snapshot.val() 收到的数据并根据键将其推送到数组)
问题描述
我想根据用户键循环从 snapshot.val()
收到的数据并将它们推送到数组中.我尝试在 for..in 这样的循环的帮助下做到这一点,
I want to loop through the data I receive from snapshot.val()
based on user keys and push them into an array. I tried doing it with the help of for..in loop like this,
firebase.database().ref('interests').child("I would like to dine with").on('value', (snapshot) => {
var data = snapshot.val();
if(snapshot.exists()){
for(let key in data){
console.log("data[key]",data[key]);
this.intVal.push(data[key]);
console.log("intVal",this.intVal);
}
}
})
但我得到了这样的东西,
But I'm getting something like this,
如果您注意到,我的第一个数组在用户键下包含 1 个对象,而我的第二个数组在其用户键下包含 3 个对象.如何将每个值推送到单独的数组中?
If you notice, my first array contains 1 object under a user key and my second array contains 3 objects under their user keys. How can I push every single value in a separate array?
任何帮助将不胜感激!谢谢
Any help would be much appreciated! Thanks
推荐答案
有一个 DataSnapshot.forEach()
方法 正是为了这个目的:
There is a DataSnapshot.forEach()
method precisely for this purpose:
firebase.database().ref('interests').child("I would like to dine with").on('value', (snapshot) => {
snapshot.forEach((child) => {
console.log(child.key, child.val());
this.intVal.push(child.val());
console.log("intVal",this.intVal);
});
}
})
这篇关于如何遍历从 snapshot.val() 收到的数据并根据键将其推送到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何遍历从 snapshot.val() 收到的数据并根据键将其推送到数组


- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01