Below is an example to consider:
Firstly, we create an object and assign it to a variable foo
. Afterwards, we assign foo
to bar
. This results in both foo
and bar
referring to the same object, as shown in the diagram below.
let foo = { id: 1, val: "foo" };
let bar = foo;
https://i.sstatic.net/yIYoj.png
Next, we modify the val
field of the object that bar
is pointing to. This change is mirrored in both variables foo
and bar
because they both reference the same object.
let foo = {id: 1,val: "foo"};
let bar = foo;
bar.val = "bar";
console.log(foo, bar);
https://i.sstatic.net/9mn8A.png
Subsequently, we assign a new object to bar
. It's important to note that this action does not impact the object that foo
is linked to; rather, bar
now references a different object.
let foo = { id: 1, val: "foo" };
let bar = foo;
bar = { id: 1, val: "bar" };
console.log(foo, bar);
https://i.sstatic.net/ly88y.png
To connect this concept to the forEach
example in your query, during each iteration of the forEach
loop, the item
parameter in the callback function points to an object from the array. Altering a field in this item
parameter will impact the corresponding object in the array. However, assigning a new object to item
will not affect the object in the array.
If you wish to substitute the entire object with a new one, there are various approaches to consider, two of which are outlined below:
- Locating the index where the object is stored and replacing it with a new object.
const arr = [{ id: 1, value: 1 }, { id: 2, value: 2 }, { id: 3, value: 3 }, { id: 4, value: 4 }, { id: 5, value: 5 }];
const index = arr.findIndex((obj) => obj.id === 3);
if (index !== -1) {
arr[index] = { id: 6, value: 6 };
}
console.log(arr);
- Another common approach is to use
map
to create a new array with the desired object replaced.
const arr = [{ id: 1, value: 1 }, { id: 2, value: 2 }, { id: 3, value: 3 }, { id: 4, value: 4 }, { id: 5, value: 5 }];
const newArr = arr.map((obj) => (obj.id === 3 ? { id: 6, value: 6 } : obj));
console.log(newArr);