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!
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);
只需使用Object.keys
然后映射到name
属性:
Object.keys(countriesList).map(x => ({[x]: countriesList[x].name}))
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"
},
}
]
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.