I have the folowing code
seriesTitles = ['depth','incline']
var aSeries = {name: '',data: [{}]}
var seriesArray = []
seriesTitles.forEach(element => { // outer loop}
aSeries.name = element;
seriesArray.push(aSeries)
})
console.log(seriesArray)
But something is wrong. It seems to add the last item in the seriesTitles array twice!
The output I get is..
{"name": "incline","data": [{}]}
{"name": "incline","data": [{}]}
When I run the code I would expect to see..
{"name": "depth","data": [{}]}
{"name": "incline","data": [{}]}
I am new to javascript and am thrown by this. Can anyone please point out where I am going wrong?
3
Answers
This is because, the object literals in JavaScript are reference variables, and you are pushing the exact same object to the array. So, its like pushing the same address of the object multiple times. So, whenever you make any change somewhere, the whole array seems to change because all the objects are same. You can read more about it here https://academind.com/tutorials/reference-vs-primitive-values
You can create a copy of the object and then make changes to the properties and then push it to the array. You can use destructuring to make a copy.
You are adding the
aSeries
twice, and happen to modify thename
. If you want differentaSeries
objects, then either make a copy or change the scope and create it inside of the forEach.You could make a copy using the spread operator:
Or just move the declaration of the
aSeries
variable inside of the for loop, so that you instantiate a new one each time.Here is the working example: