如何从对象的对象创建对象数组?

时间:2021-07-28 18:06:00

标签: javascript arrays 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"
  },
}

object,不是array,而且很重要。我想创建新数组,它看起来像这样:

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

我试图做这样的事情:

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

但是我得到的不是对象数组中的键,而是 value。我该怎么做?

感谢您的回答!

3 个答案:

答案 0 :(得分:1)

你可以map超过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);

答案 1 :(得分:0)

只需使用 Object.keys 然后映射到 name 属性:

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

答案 2 :(得分:0)

您可以使用所有键创建和类似的对象数组。

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

这会像这样返回

[
{
  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"
  },
}
]