首页 > 解决方案 > 使用 es6 将对象中的对象中的值作为数组获取

问题描述

I'm pulling data from a service that loads into a dropdown and when a value is selected it's being assigned to a variable and an example is below

[{
    "id": 482,
    "firstName": "Micheal",
    "lastName": "Bamford",
    "email": "lalacifay@cliptik.net",
    "areaCodes": [
        {
            "id": 60,
            "name": "New York",
            "status": "ACTIVE",
            "createdDate": "2018-10-30 14:09:28"
        },
        {
            "id": 12,
            "name": "Florida",
            "status": "ACTIVE",
            "createdDate": "2018-10-30 14:09:28"
        }
    ],

    "createdDate": "2019-01-03 12:29:33"
}]

我想要实现的是只在这样的对象中获取name属性areaCodes['New York', 'Florida']

下面是我到目前为止使用的代码,它只让我得到数组中的第一个

const selected = this.listFromAPI.filter(t => t.id === ev.id).map(r=> r.areaCodes[0].name);

标签: javascriptangularecmascript-6

解决方案


这是你想要的?

const dataset = [{
  "id": 482,
  "firstName": "Micheal",
  "lastName": "Bamford",
  "email": "lalacifay@cliptik.net",
  "areaCodes": [{
      "id": 60,
      "name": "New York",
      "status": "ACTIVE",
      "createdDate": "2018-10-30 14:09:28"
    },
    {
      "id": 12,
      "name": "Florida",
      "status": "ACTIVE",
      "createdDate": "2018-10-30 14:09:28"
    }
  ],

  "createdDate": "2019-01-03 12:29:33"
}];

for (const item of dataset) {
  const {
    areaCodes
  } = item;
  if (Array.isArray(areaCodes)) {
    const names = areaCodes.map(c => c.name);
    console.log(names);
  }
}


推荐阅读