2

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)
Andreas
  • 21,535
  • 7
  • 47
  • 56
sivu
  • 61
  • 1
  • 1
  • 5
  • `x.push({ ...test[0] });` – DecPK Jul 13 '21 at 07:42
  • `test[0]` is a reference to the object at index `0`. After the `.forEach()` `x` has `test2.length` copies of that one reference. – Andreas Jul 13 '21 at 07:42
  • 1
    It's a dupe of [How do I correctly clone a JavaScript object?](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object) - in some way... – Andreas Jul 13 '21 at 07:46

3 Answers3

1

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);
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • _"it will have 3 copies of object"_ - If that would be the case then the problem as observed by OP would not exist. `.push(test[0])` pushes references to the object at index `0` and not a copy of the object – Andreas Jul 13 '21 at 07:45
1

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.

Alec
  • 8,529
  • 8
  • 37
  • 63
0

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)
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39