I need to create array filled with objects. Lets say { foo: 0}
. Then I want to add property bar
to each object with different value. For example: value = index of item in array.
It looks like this
const table = new Array(10).fill({foo: 0});
for (let i = 0; i < table.length; i += 1) {
table[i].bar = i;
}
What I expected to get is:
[
{ foo: 0, bar: 0 },
{ foo: 0, bar: 1 },
{ foo: 0, bar: 2 },
...
{ foo: 0, bar: 9 }
]
And what I got:
[
{ foo: 0, bar: 9 },
{ foo: 0, bar: 9 },
{ foo: 0, bar: 9 },
...
{ foo: 0, bar: 9 }
]
Why it behaves that way? Where I made mistake?
EDIT To clarify
I don't want to replace objects in array with new object like table[i] = {foo: 0, bar: i}
. It creates new object that replaces old one.
I just want to add properties to existing object.