I’m creating an array of objects in Javascript. The object data is being generated on the fly in a for loop.
When you run this code you’ll see that the final array generated in the console log is all the same data for each index.
I’m new to Javascript, but I do have experience with arrays in C++, Python, VBA, etc.
I realize there are other types of loops for arrays like ForEach, and Mapping, but
this seems like it should be very straightforward, but I have no idea what I’m missing.
const test_data = {
value: 0,
value2: 0
};
let number = 10;
let test_array = [];
let temp = test_data;
for (let i = 0; i < number; i++) {
//i realize using a temp object is a little redundant
//being that i could just say test_array[i].value = ***
//i get the same results either way.
temp.value = 500 * (i + 1);
temp.value2 = temp.value * 100;
test_array.push(test_data);
test_array[i] = temp;
console.log(temp);
console.log(test_array[i]);
console.log(test_array);
}
console.log(test_array);
3
Answers
Objects are passed by reference in JS, so in your code on each iteration you are modifying the same object and adding a link to it in your array.
You will have to either create copies of the
temp
object whenever you add it to the array or, since you modify all properties, create a new object and set it before adding it.Or if you wan to create copies from the original (because there are other data you want to keep)
Finally, if you want to create copies and the
test_data
holds other objects in it, you might want to do a deep copy insteadAs @Stephen Quan mentioned in his comment you have multiple reference and reference to the same object.
To solve this issue you can use the spread operator to create the new copy of the object.
Check if this is what you are looking for
Output: