I am fetching some data from my firebase database and structuring the data in an object and storing each object in an array but it is only storing the 1st object multiple times and not storing 2nd 3rd ... or Nth object I am using a loop for storing them but can't figure out what is wrong please look into the function below
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
}
this is the output I am getting please notice that I am successfully fetching different objects from my database but it's not pushing all of them its only printing object number 1 twice
To understand what the issue here is, you got to know the difference between References and Values.
In Javascript Object and Arrays are stored into memory by their reference. Where as Primitive datatypes such as Number, String, Boolean are stored by value.
Lets say I am creating an Object as
myObj = {firstName: "First", lastName: "last"}
In this case myObj will store the memory reference of myObj and not the value. If you assign this object to another variable, it will not copy the value of object, instead you are only copying the reference to another variable.
copyObj = myObj
The following operation will not only change copyObj but myObj as well becuase both variable are pointing to exact same Object (Hash map) in memory.
copyObj.firstName = "New First Name
Now coming to your problem
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
}
Your for loop is pointing to the same data object, assigning some values to it and pusing it into the array.
In first Iteration it will update data object and push it into array. (Remember that it will only push the reference).
In 2nd and subsequent iteration, you are only updating already existent data object and not creating a new one hence all the variables in your array pointing to same data object will have same value.
Creating a new Object (a new reference to a new HashMap) every time inside the array will resolve your issue.
for (let i = 0; i < roomList.length; i++) {
const data = {};
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
}
I would really suggest you to read a Article on Copying objects and arrays. Also Shallow copy vs Deep Copy.