js数据处理总结

背景

平常开发过程当中,咱们常常会碰到须要对一些数据进行处理的状况,索性就整理个文档吧,方便往后查阅。javascript

javascript 中数组对象求交集、并集、补集

以下代码:java

const a = [
        {
        'categoryId': 1,
        'categoryIdLevelOne': 750611334,
        'categoryIdLevelThree': 750611336,
        'categoryIdLevelTwo': 750611335,
        'id': 2697,
        'level': 3,
        'shopId': 12430,
        'skipLayoutFlag': false,
        'status': 1
    },
    {
        'categoryId': 2,
        'categoryIdLevelOne': 750611472,
        'categoryIdLevelTwo': 750611473,
        'id': 2701,
        'level': 2,
        'shopId': 12430,
        'skipLayoutFlag': false,
        'status': 2
    },
    {
        'categoryId': 3,
        'categoryIdLevelOne': 750611487,
        'categoryIdLevelTwo': 750611488,
        'id': 2702,
        'level': 2,
        'shopId': 12430,
        'skipLayoutFlag': false,
        'status': 1
    }
    ]
    const b = [
        {
        'categoryId': 2,
        'categoryIdLevelOne': 750611334,
        'categoryIdLevelThree': 750611336,
        'categoryIdLevelTwo': 750611335,
        'id': 2697,
        'level': 3,
        'shopId': 12430,
        'skipLayoutFlag': false,
        'status': 1
    },
    {
        'categoryId': 3,
        'categoryIdLevelOne': 750611472,
        'categoryIdLevelTwo': 750611473,
        'id': 2701,
        'level': 2,
        'shopId': 12430,
        'skipLayoutFlag': false,
        'status': 2
    },
    {
        'categoryId': 4,
        'categoryIdLevelOne': 750611487,
        'categoryIdLevelTwo': 750611488,
        'id': 2702,
        'level': 2,
        'shopId': 12430,
        'skipLayoutFlag': false,
        'status': 1
    }
    ]
复制代码
  • 交集
const c = a.filter( a => b.some(b => b.categoryId  === a.categoryId))
复制代码
  • 补集(差集)
const d = a.filter(x => b.every(y => y.categoryId !== x.categoryId))
复制代码
  • 并集
const e = b.filter(y => a.every(x => x.categoryId !== y.categoryId)).concat(a)
复制代码