0

I have such object:

  const countriesList = {
  NAC: {
    name: 'NAC'
  },
  LEVANT: {
    name: 'Levant'
  },
  GCC: {
    name: 'Gulf Cooperation Council',
    iso2: 'GC',
    code: '96'
  },
  AF: {
    name: "Afghanistan",
    iso2: "AF",
    code: "93"
  },
  AL: {
    name: "Albania",
    iso2: "AL",
    code: "355"
  },
}

It's object, not array and it's important. I want to create new array, which is gonna look like that:

const result = [
  {NAC: 'NAC'},
  {LEVANT: 'Levant'},
  {GCC: 'Gulf Cooperation Council'},
  {AF: "Afghanistan"},
  {AL: "Albania"}
]

I was trying to do something like that:

for (let value in countriesList) {
  let temp = {
    value: countriesList[value]['name']
  }
  this.countries.push(temp)
  temp = {}
}

But instead of keys in array of objects I got value. How can I do that?

Thanks for answers!

0

3 Answers 3

1

You can map over Object.entries.

const countriesList = {
  NAC: {
    name: 'NAC'
  },
  LEVANT: {
    name: 'Levant'
  },
  GCC: {
    name: 'Gulf Cooperation Council',
    iso2: 'GC',
    code: '96'
  },
  AF: {
    name: "Afghanistan",
    iso2: "AF",
    code: "93"
  },
  AL: {
    name: "Albania",
    iso2: "AL",
    code: "355"
  },
}
const res = Object.entries(countriesList).map(([key, {name}])=>({[key]: name}));
console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

0

Just use Object.keys then map to the name property:

Object.keys(countriesList).map(x => ({[x]: countriesList[x].name}))

Comments

0

You can Create and similar Array of Object with all the Keys.

const countryList = Object.entries(countriesList).map((e) => ( { [e[0]]: e[1] } ));

This Will Return Like This

[
{
  NAC: {
    name: 'NAC'
  },
  LEVANT: {
    name: 'Levant'
  },
  GCC: {
    name: 'Gulf Cooperation Council',
    iso2: 'GC',
    code: '96'
  },
  AF: {
    name: "Afghanistan",
    iso2: "AF",
    code: "93"
  },
  AL: {
    name: "Albania",
    iso2: "AL",
    code: "355"
  },
}
]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.