I have an array of objects and assigned their properties and values using Array.prototype.fill()
. I want to assign a new value to a property of a specific element in the array.
For example:
let data = Array(3).fill({test_1: 0, test_2: true});
function f(index) {
data[index].test_1 = 5;
console.log(data);
}
f(0);
However, instead of assigning that value to that specific object's property, all of the objects in the array have their own property assigned that same value.
Here is the output:
// Actual result
[
{
test_1: 5,
test_2: true
},
{
test_1: 5,
test_2: true
},
{
test_1: 5,
test_2: true
}
];
// Expected result
[
{
test_1: 5,
test_2: true
},
{
test_1: 0,
test_2: true
},
{
test_1: 0,
test_2: true
}
];
Instead of only the first object getting 5 as its value for the test_1
property, all three objects have 5 as their value for their test_1
properties.
So, my questions are:
- Why is
f()
assigning the same value to the same property of all the elements in the array? - How can I assign a value to a property of only a specific element of the array?