0

Hello I wanted to make an json array like below from for loop

 { id: 1, itemName: "USA" }, { id: 2, itemName: "UK" }, { id: 3, itemName: "India" }, { id: 4, itemName: "Canada" }, { id: 5, itemName: "Germany" }, { id: 6, itemName: "China" } 

I have writen this code for this

 data.Countries.forEach(element => { this.countryInfo.push( 'id:'+i, 'itemName:'+ element.CountryName); i++; }); 

but this not working, please help me for this

2

2 Answers 2

2

You could use the Array map function. Try the following

this.countryInfo = data.Countries.map((country, index) => ({'id': index + 1, 'itemName': country.CountryName}) ); 
    1

    Use the below code:

     data.Countries.forEach((element,index) => { this.countryInfo.push({ 'id':index+1, 'itemName':element.CountryName }); }) 
    0

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.