gpt4 book ai didi

javascript - 如何循环遍历我从 snapshot.val() 收到的数据并将其推送到基于键的数组

转载 作者:可可西里 更新时间:2023-11-01 02:04:54 25 4
gpt4 key购买 nike

我想根据用户键遍历从 snapshot.val() 收到的数据,并将它们推送到一个数组中。我尝试在 for..in 循环的帮助下这样做,

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);
}
}
})

但是我得到了这样的东西,

enter image description here

如果您注意到,我的第一个数组在用户键下包含 1 个对象,而我的第二个数组在其用户键下包含 3 个对象。如何将每个值推送到单独的数组中?

任何帮助将不胜感激!谢谢

最佳答案

有一个DataSnapshot.forEach() method正是为了这个目的:

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);
});
}
})

关于javascript - 如何循环遍历我从 snapshot.val() 收到的数据并将其推送到基于键的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46143891/

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