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

0

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

Object.keys(countriesList).map(x => ({[x]: countriesList[x].name}))
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"
  },
}
]

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.