猿问

怎么过滤数组

刚开始的两个数组是这样的,b数组是在a数组的基础上加了一个字段
a=[{
label:'周一',
organizeId:'1001'
},{
label:'周二',
organizeId:'1002'
},{
label:'周三',
organizeId:'1003'
},{
label:'周四',
organizeId:'1004'
},{
label:'周五',
organizeId:'1005'
}]
b=[{
children:[{
label:'周一',
organizeId:'1001',
subValue:'100'
},{
label:'周二',
organizeId:'1002',
subValue:'200'
},{
label:'周三',
organizeId:'1003',
subValue:'1000'
},{
label:'周四',
organizeId:'1004',
subValue:'800'
},{
label:'周五',
organizeId:'1005',
subValue:'600'
}]
},{
children:[{
label:'周一',
organizeId:'1001',
subValue:'100'
},{
label:'周二',
organizeId:'1002',
subValue:'200'
},{
label:'周三',
organizeId:'1003',
subValue:'1000'
},{
label:'周四',
organizeId:'1004',
subValue:'800'
},{
label:'周五',
organizeId:'1005',
subValue:'600'
}]
}]
当a的数据变化之后
a=[{
label:'周一',
organizeId:'1001'
},{
label:'周二',
organizeId:'1002'
},{
label:'周六',
organizeId:'1006'
}]
我想得到这样的数组,之前有的数据不变,没有的比如周六,就加上并将subValue值设为0,去掉的,比如周三,周四,周五,新的数组里的children里也去掉
b=[{
children:[{
label:'周一',
organizeId:'1001',
subValue:'100'
},{
label:'周二',
organizeId:'1002',
subValue:'200'
},{
label:'周六',
organizeId:'1006',
subValue:'0'
}]
},{
children:[{
label:'周一',
organizeId:'1001',
subValue:'100'
},{
label:'周二',
organizeId:'1002',
subValue:'200'
},{
label:'周六',
organizeId:'1006',
subValue:'0'
}]
}]
慕后森
浏览 600回答 2
2回答

摇曳的蔷薇

constnewA=[{label:'周一',organizeId:'1001',},{label:'周二',organizeId:'1002',},{label:'周六',organizeId:'1006',},]//找出新增的项constaddArr=newA.filter(d=>!a.find(d1=>d1.organizeId===d.organizeId))b=b.map(item=>{letchild=[...item.children]//过滤没有的项child=child.filter(c=>newA.find(n=>n.organizeId===c.organizeId))//添加新增的项addArr.forEach(d=>child.push({...d,subValue:0}))return{child}})

芜湖不芜

b.forEach(n=>{constchildren=n.children;constnewChildren=children.filter(o=>a.some(i=>i.label===o.label));constoldChildren=a.filter(o=>children.every(i=>i.label!==o.label)).map(o=>{o.subValue="0";returno;});n.children=newChildren.concat(oldChildren);});console.log(b);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答