iterate array and populate with json data

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?

>Solution :

You are adding the aSeries twice, and happen to modify the name. If you want different aSeries 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:

seriesTitles = ['depth','incline']      
const seriesArray  = []
const aSeries = {name: '',data: [{}]};
seriesTitles.forEach(element => { // outer loop
  aSeries.name = element;
  seriesArray.push({...aSeries});    
})
console.log(seriesArray)

Or just move the declaration of the aSeries variable inside of the for loop, so that you instantiate a new one each time.

seriesTitles = ['depth','incline']      
const seriesArray  = []

seriesTitles.forEach(element => { // outer loop
  const aSeries =  {name: '',data: [{}]}
  aSeries.name = element;
  seriesArray.push(aSeries);    
})
console.log(seriesArray)  

Leave a Reply