如何快速抓取对象数组中某个属性的集合?

如何快速抓取对象数组中某个属性的Key的集合?

  • 输入数据格式如下 ,要求抓取operations之所有Key的不重复的集合, 形如[‘free’,‘close’]等。
const data = [
   {id: 1, label: '全部', billStatus: 'alldata', number: 0, pId: 0 },
   {id: 2, label: '待提交', billStatus: 'free', number: 0, pId: 0, filter: 'free', operations: { free: '制作', close: '异常关闭', back: '退回需求', } },
   {id: 3, label: '待会签', billStatus: 'commit', number: 0, pId: 0, filter: 'commit', operations: { commit: '会签', followup: '跟催' } },
   {id: 4, label: '待审批', billStatus: 'approve', number: 0, pId: 0, filter: 'approve', operations: { approve: '审批', followup: '跟催' } },
   {id: 5, label: '审批通过', billStatus: 'approvepass', number: 0, pId: 0, filter: 'approvepass', operations: { view: '查看', } },
   {id: 6, label: '异常关闭', billStatus: 'close', pId: 0, },
   {id: 7, label: '异常关闭审批中', billStatus: 'closeapprove', number: 0, pId: 6, filter: "closesign", operations: { followup: '跟催', view: '查看' } },
   {id: 8, label: '异常关闭通过', billStatus: 'closeapprovepass', number: 0, pId: 6, filter: "closeapprovepass", operations: { view: '查看' } },
   {id: 9, label: '退回需求', billStatus: 'back', number: 0, pId: 0, filter: "back", operations: { view: '查看' } }     
]

代码下

Object.keys(Object.assign({},...data.filter(item=>Boolean(item.operations)).map(item=>item.operations)))

思路及涉及的API、知识点如下

  1. data.filter(item=>Boolean(item.operations)) 这条语句的作用是返回有operations这个属性的数据项,即去掉没有operations属性的数据项

    Boolean(item.operations)是隐形条件判断,完整写法:Boolean(item.operations) ===true, 这好比我们天天使用if(some){ },
    其实它的完整写法是 if(some === true) { }
    data.filter的作用是将满足条件的数据项以数组的格式(原格式)返

  2. map(item=>item.operations) 只返回数据项中的operations属性之值的集合

    [ {id:1, name:‘张三’, score:80}, {id:2, name:‘李四’, score:90},{id:3, name:‘王五’, score:75} ].map(item=>item.score) = [80, 90, 75] ;
    上述示例只返回了score属性值的集合

  3. … 即3个点,为ES6的解构语法, 常用于数组和对象,可展开里面的元素或属性

    const arr = [ {id:1, name:‘张三’, score:80}, {id:2, name:‘李四’, score:90},{id:3, name:‘王五’, score:75} ] ;
    …arr 等同于 {id:1, name:‘张三’, score:80}, {id:2, name:‘李四’, score:90},{id:3, name:‘王五’, score:75}

  4. Object.assign(参数1,参数2,…参数n)

    它的参数通常都是对象类型,即键值对形式,作用就是将参数2及后续的所代表的对象合并入参数1中去,并返回参数1。
    const obj = {a:1,b:2,c:3} Object.assign(obj,{c:13,d:4},{d:40,e:5}) 输出 {a: 1, b: 2, c: 13, d: 40,e:5},如果有重复属性,则后者会覆盖前者

  5. Object.keys()

    用于返回对象的键的集合, Object.keys({a: 1, b: 2, c: 13, d: 40,e:5}) 输出 [“a”, “b”, “c”, “d”, “e”]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值