0

Disclaimer: I don't know what's the proper title for this issue that I have, so any edit is welcomed.

I have an array of objects. For each object I want to change the value of one property. After I change the value with forEach() function the initial data is also changed, which is not what I want. I have attached a pen so you can understand better.

Could you please have a look and explain why JS have this behavior?

Thank you!

Daniel Turuș
  • 596
  • 6
  • 19
  • please add all relevant information to the question. please have a look here, too: [mcve] – Nina Scholz Jul 28 '18 at 20:01
  • possible duplicate: https://stackoverflow.com/questions/35922429/why-a-js-map-on-an-array-modify-the-original-array – Bob Jul 28 '18 at 20:08

1 Answers1

0

The object within your array are passed by reference - meaning that whatever change they would undergo within the forEach function will alter 'the original'' object as well. One example for what you can do is: result = Object.assign({}, element); Instead of result = element; The Object.assign Will create a new copy of that object and you won't be altering your original array.

MDN for Object.assign

Edit:

In other words, JavaScript isn't creating a new object when you iterate over an array of objects. So while iterating, element is the the same object as in currencyRates array. And when assigning result = element result is also the same object. Both pointing to the same array, just with different names. So when your modifying result is like modifying element or alternatively modifying directly in the array - i.e. currencyRates[0][nameOfTheDateKey] = newValue. When using Object.assign JS creates a new copy of element in results, and it is no longer the same object, thus manipulating it won't affect element and in turn won't affect your original array. Hope it is cleared and makes more sense now.

DSCH
  • 2,146
  • 1
  • 18
  • 29