怎么过滤数组

Unicorn
  • 91

刚开始的两个数组是这样的,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'
    }]
  }]
回复
阅读 836
2 个回答
const newA = [
  {
    label: '周一',
    organizeId: '1001',
  },
  {
    label: '周二',
    organizeId: '1002',
  },
  {
    label: '周六',
    organizeId: '1006',
  },
]
// 找出新增的项
const addArr = newA.filter(d => !a.find(d1 => d1.organizeId === d.organizeId))
b = b.map(item => {
  let child = [...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 => {
    const children = n.children;
    const newChildren = children.filter(o => a.some(i => i.label === o.label));
    const oldChildren = a.filter(o => children.every(i => i.label !== o.label)).map(o => {
        o.subValue = "0";
        return o;
    });
    n.children = newChildren.concat(oldChildren);
});
console.log(b);
你知道吗?

宣传栏