如何基于属性值从对象中提取

时间:2019-07-16 20:28:59

标签: javascript ecmascript-6

我有一个对象数组,想根据属性提取值

let obj = [
    {
      "name": "USA",
      "type": "Required",
    },
    {
      "name": "Australia",
      "type": "Discontinued",
    },
    {
      "name": "Austria",
      "type": "Optional",
    } ,
  {
      "name": "Argentina",
      "type": "Required",
    } 
]

我试图根据这样的类型从该对象数组中提取

let arr = obj.map((cc)=>{ if(cc["type"] == "Required"){
  return cc["type"]
} })

现在,我得到的结果为[“ Required”,未定义,undefined,“ Required”]

但是,我希望数组仅包含[“ Required”,“ Required”]

3 个答案:

答案 0 :(得分:1)

在地图上使用过滤器

let arr = obj.filter((cc)=> cc["type"] == "Required").map( cc => cc.type);

答案 1 :(得分:0)

如果您要迭代一次,则可以使用reduce

obj.reduce((a, e) => e.type === 'Required' ? a.concat(e.type) : a, [])

答案 2 :(得分:0)

您将要使用filter,然后使用map,如其他答案所示:

let arr = obj.filter(cc => cc.type=="Required").map(cc => cc.type);

反之亦然,因为您的情况始终基于地图结果:

let arr = obj.map(cc => cc.type).filter(val => val=="Required");

但是,如果您想一步一步做,我建议flatMap

let arr = obj.flatMap(cc => cc.type=="Required" ? [cc.type] : []);