简体   繁体   中英

Cannot populate an array from JSON object in Angular

I have the following JSON object:

Object { JP: "JAPAN", PAK: "PAKISTAN", IND: "INDIA", AUS: "AUSTRALIA" }

This JSON is a response data returned from a get call(HttpClient Angular) .

So now, I need to populate this into the following to display as a dropdown list.

countryList: { countryCode: string; countryName:string }[];

I tried doing the following:

for (const key in resData) {
  if (resData.hasOwnProperty(key)) {
     var obj ={
       countryCode :key,
       countryName : resData[key]
      }
    this.countryList.push(obj);
  }
}

But when I execute I'm getting this error

"_this.countryList.push is not a function"

What am I doing wrong?

The code you've posted only defines the type of countryList. You need to also initialise it as an empty array before you can push to it - see below.

countryList: { countryCode: string;countryName :string }[] = [];

You can get entries from the object and then map it to the array of objects:

Object.entries(countries).map(([key, value]) => ({
     countryCode: key,
     countryName: value
}))

you need to declare countryList as list.

 var resData={ JP: "JAPAN", PAK: "PAKISTAN", IND: "INDIA", AUS: "AUSTRALIA" }; countryList=[]; for (const key in resData) { if (resData.hasOwnProperty(key)) { var obj ={ countryCode:key, countryName: resData[key] } countryList.push(obj); } } console.log(countryList)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM