简体   繁体   中英

How to extract from object based on value of a property

I have an array of objects, wanted to extract values based on the property

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

I have tried to extract from that array of objects based on type like this,

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

Now, I am getting result as, ["Required", undefined, undefined, "Required"]

But, I am expecting array containing only ["Required", "Required"]

在地图上使用过滤器

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

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

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

You'll want to use filter followed by map , as demonstrated in the other answers:

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

or the other way round, since your condition is based on the map result anyway:

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

But if you want to do it in one step, I would recommend flatMap :

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM