参考文档:
- 使用基于嵌套值的数组过滤对象数组: https://segmentfault.com/q/1010000042989861
- js 扩展运算符(...)的用法 :https://www.cnblogs.com/caihongmin/p/16395573.html
- 对象的扩展运算符: https://blog.csdn.net/weixin_42265852/article/details/88739525
- Vue判断对象中是否存在某个属性: https://blog.csdn.net/gltncx11/article/details/109491728
初始数据如下:
const cards = [ { name: "myMember", nameZH: "我的会员卡", cardAuth: 1, value: [ { name: "预约", subAuth: "update", }, { name: "查询", } ] }, { name: "oilStationManage", nameZH: "历史记录", cardAuth: 0, value: [ { name: "消费记录", subAuth: "read", }, { name: "交易记录", subAuth: "read", }, ] }, { name: "workersManage", nameZH: "员工管理", cardAuth: 1, value: [ { name: "销售员工", subAuth: "read", }, { name: "技术员工", } ] } ];
我想找出 cardAuth==1、有“subAuth”属性的值组成的数组,也就是:
输出结果
[ { name: "myMember", nameZH: "我的会员卡", cardAuth: 1, value: [ { name: "预约", subAuth: "update", }, ] }, { name: "workersManage", nameZH: "员工管理", cardAuth: 1, value: [ { name: "销售员工", subAuth: "read", }, ] } ]
我在 https://segmentfault.com/q/1010000042989861 找到了一个完全符合我要求的答案,但是代码看上去很复杂,在这里记录一下代码解释:
先验知识:
- js 判断对象中是否存在某个属性可以用 in 和 hasOwnProperty
var obj = { a:2 }; ("a" in obj); // true ("b" in obj); // false obj.hasOwnProperty( "a" ); // true obj.hasOwnProperty( "b" ); // false
- 扩展运算符 ...
定义: 扩展运算符(...)是ES6的语法,用于取出参数对象的所有可遍历属性,然后拷贝到当前对象之中。
自定义的属性在拓展运算符后面,则拓展运算符对象内部同名的属性将被覆盖掉。
let person = {name: "Amy", age: 15}; { ...person, name: "Mike", age: 17}; // {name: 'Mike', age: 17}
代码解释:
- 过滤出 cardAuth == 1 的值, 用 let authCards = cards.filter(card=>card.cardAuth == 1)
- 在第一步的基础上,过滤二级对象的数组属性值 authCards.map(e=>{ return {...e,value:e.value.filter(ee=>"subAuth" in ee)} })
cards.filter(card=>card.cardAuth == 1) 运行结果:
authCards.map(e=>{ console.log(e); })
authCards.map(e=>{ console.log(e.value) })
authCards.map(e=>{ e.value.filter(ee=>{ if("subAuth" in ee){ console.log(ee) } }) })
authCards.map(e=>{ e.value.filter(ee=>{ if("subAuth" in ee){ console.log({...ee}) } }) })
authCards.map(e=>{ e.value.filter(ee=>{ if("subAuth" in ee){ console.log({...ee,subAuth:666}) } }) })
authCards.map(e=>{ return {...e,value:e.value.filter(ee=>"subAuth" in ee)} })
标签:filter,name,map,ee,value,运算符,cardAuth,subAuth From: https://www.cnblogs.com/sunshine233/p/18037011