Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"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)  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading