0

In this case, a is changed.

var a = [{a: 1, b: 2}, {a: 3, b: 4}, {a : 5, b : 6}];
a.forEach(x => x.a = 7);

0: {a: 7, b: 2}
1: {a: 7, b: 4}
2: {a: 7, b: 6}

But in this case a is not changed.

var a = [{a: 1, b: 2}, {a: 3, b: 4}, {a : 5, b : 6}];
a.forEach(x => x = {...x, a:7});

0: {a: 1, b: 2}
1: {a: 3, b: 4}
2: {a: 5, b: 6}

what is difference?

erin
  • 1
  • 1
  • 2
    Spread syntax shallow-clones the object, so the original object (in the array) remains unchanged – CertainPerformance Jan 07 '20 at 00:45
  • 1
    `forEach` calls your function with each element of the array as an argument. Assigning a new object to the parameter `x` won’t change anything else (e.g. the array). `x.a = 7` is different because it’s changing the object itself, rather than changing a variable, and the array holds that same object. – Ry- Jan 07 '20 at 01:01
  • 1
    Related: https://stackoverflow.com/questions/46762112/why-is-my-foreach-loop-not-editing-my-array – Ry- Jan 07 '20 at 01:03
  • a.forEach((value, i)=> { a[i].a = 7; }); you can try like this. This basically edits your a variable. – Jenuel Ganawed Jan 07 '20 at 01:54

0 Answers0