0

I have an object array:

const test = new Array(2).fill({ a: 1, b: 2 });

test[0].a = 3;

I just want to reassign "a" in the first object, but when I use the above code, both "a" gets reassigned. And the output:

[ { a: 3, b: 2 }, { a: 3, b: 2 } ]
webber
  • 595
  • 3
  • 10
  • 20
  • If it's the same reference, then it will also be changed. This is the general rule for objects, excluding primitive values. –  Sep 08 '20 at 09:55

1 Answers1

0

As stated in eg this documentation of the Array fill method

If the first parameter is an object, each slot in the array will reference that object.

A possible solution:

const test = Array.from({ length: 2 }).map(() => ({ a: 1, b: 2 }));

test[0].a = 3;

console.log(test);
36ve
  • 513
  • 4
  • 12