0

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?

3 Answers 3

2

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 }[] = [];
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, have done so. Could you suggest me a way to close this thread?
Thanks! Everything on the site just stays up. That way if someone has a similar issue, hopefully your question will help them too.
Okay. Thank you once again.
1

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
}))

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.