首页 > 解决方案 > 如何通过存储在数组中来制作对象列表

问题描述

我正在从我的 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 两次

在此处输入图像描述

标签: javascriptarraysdata-structureslogicjavascript-objects

解决方案


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

推荐阅读