I'm trying to do a single loop and update an object property with each loop value but something unexpected happens:
The first console.log prints the day object property updated as expected. The second one, however, which prints the full object, shows the day property with the value of the final forEach value.
Example:
data.days = [ 5, 6 ]
First loop prints:
newData.date: 5
{prop1: x, prop2: x...., date: 6}
Second loop prints:
newData.date: 6
{prop1: x, prop2: x...., date: 6}
This is the my code:
data.days.forEach(day => {
let newData;
newData = data.data;
newData.date = day;
console.log('newData.date: ' + newData.date)
console.log(newData)
})
I've tried to create the newData variable out of forEach or a for loop instead, but I have the same result.


data.days = { 5, 6 }is invalid syntaxnewData = data.datais copy by reference, you're actually assigning the same object on every loop. That's why you always get the last value in the final loop...