How to fix auto update array in javascript

Viewed 454

that is suppose to come 1,2,3 but coming 3,3,3, how to fix that ? Javascript updating automatically

let test = [ { id: 1 } ];
let test2 = [
  { id: 1 },
  { id: 2 },
  { id: 3 }
];

let x = []

test2.forEach(i => {
  test[0].id = i.id;
  x.push(test[0])
});

console.log(x)

3 Answers

Since you are pushing the same object 3 times and at the end of the loop it will have 3 reference of the same object i.e test[0]

You can use spread syntax to copy all properties of object

let test = [{ id: 1 }];
let test2 = [{ id: 1 }, { id: 2 }, { id: 3 }];

let x = [];

test2.forEach((i) => {
  test[0].id = i.id;
  x.push({ ...test[0] });
});

console.log(x);

Use the spread operator:

x.push({ ...test[0] })

Basically you need to shallow clone the array because it's an object; forEach will create 3 references to the same test[0] object at the beginning of the call.

You are passing in the same reference to the array everytime. You are updating that same value too i.e., test[0].

So in the end, you have an array with three elements, all 3 pointing to the same object whose id property you have updated to the final value - test2[2].id.

You can directly push in an object with the correct id property. You will not need an extra test array as you are creating your object and pushing them on the go.

let test = [ { id: 1 } ];
let test2 = [
  { id: 1 },
  { id: 2 },
  { id: 3 }
];

let x = []

test2.forEach(i => {
  x.push({ id : i.id })
});

console.log(x)

Related