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!

asked Jul 28, 2021 at 18:06
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);

answered Jul 28, 2021 at 18:07
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}))
answered Jul 28, 2021 at 18:08

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"
 },
}
]
answered Jul 28, 2021 at 18:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.