javascript - 如何通过存储在数组中来制作对象列表
问题描述
我正在从我的 firebase 数据库中获取一些数据并将数据构造在一个对象中并将每个对象存储在一个数组中,但它只存储第一个对象多次而不存储第二个第三个......或第 N 个对象我正在使用循环存储它们但无法找出问题所在,请查看下面的函数
function dataHandler(deviceList,roomList) {
var data = {
roomName: "",
devicesAssigned: [] ,
};
for (let i = 0; i < roomList.length; i++) {
data.devicesAssigned = deviceList[i];
data.roomName = roomList[i];
console.log(data);//printing object getting from database
dataArray.push(data);// storing each object in an array
}
console.log(dataArray);// printing after array is filled
}
这是我得到的输出请注意,我成功地从我的数据库中获取不同的对象,但它并没有将它们全部推送,它唯一的打印对象编号 1 两次
解决方案
You're pushing the same data
object onto the array every time. You need to create a new object each time through the loop.
function dataHandler(deviceList, roomList) {
for (let i = 0; i < roomList.length; i++) {
var data = {
roomName: roomList[i],
devicesAssigned: deviceList[i],
};
console.log(data); //printing object getting from database
dataArray.push(data); // storing each object in an array
}
console.log(dataArray); // printing after array is filled
}
You can also get rid of the for
loop and do it all in one call to map()
.
dataArray = roomList.map((room, i) => ({
roomName: room,
devicesAssigned: deviceList[i]
}))
推荐阅读
- c++ - 使用在“if”内部声明的类/结构成员,外部有条件
- ibm-cloud - Watson Studio:不处理图像
- python - 无法激活我的虚拟环境,因为激活文件未显示
- django - Django All-Auth 未重定向到 LOGIN_URL
- linux - 如何重命名批处理文件
- javascript - 如何从 csvtojson 范围内获取 JSON 数据?
- php - php 显示带有分页的数组项
- android - 将 Firebase 数据快照反序列化为 Kotlin 数据类
- python - 无法安装 pipenv python 版本
- python - 根据 Dataframe 中匹配的 ID 更新 SQL 数据库