Search code examples
javascriptarraystypescriptjavascript-objects

Changing a value in first object results in second object change


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 } ]

Solution

  • 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);