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.