• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: JS forEach traverses the problem of modifying objects

Resolved: JS forEach traverses the problem of modifying objects

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

Why does the first modification work (when I reassign properties of the object) but not the second (when I reassign the whole object)?


Answer:

Consider the example below:
We create an object and assign it to variable foo and then we assign foo to bar. So, now both foo and bar refer to the same object, as illustrated in the diagram below.
enter image description here
Next let’s change the val field of the object i.e. assigned to bar. We notice that the change is reflected by both the variables foo and bar and this is because both the variables refer to the same object.


enter image description here
Next we assign a new object to bar. Notice this doesn’t effect the object that foo refers to, bar is simply now referring to a different object.


enter image description here
Let’s relate this to the forEach example in your question. So, in every iteration of the forEach loop, the item argument in the callback function points to an object from the array and when you change a field from this item argument it changes the object in the array but when you assign item to a new object it does nothing to the object stored in the array.
If you want to replace the entire object with a new one, there are several approaches you could take, two of which are mentioned below:
  1. Finding the index where the object is stored and replacing it with a new object.



  1. Another really common approach is to map over the array and create a new array with that one object replaced.



If you have better answer, please add a comment about this, thank you!

foreach-object javascript
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Reshape tensors of unknown shape with tf.function

26/03/2023

Resolved: Use Svelte Component as Slot

26/03/2023

Resolved: Vaadin 14.9 – Redirect on Session Destroy Event

26/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.