js数组对象根据id去重

 var arr = [{
      key: '01',
      value: '乐乐'
    }, {
      key: '02',
      value: '博博'
    }, {
      key: '03',
      value: '淘淘'
    }, {
      key: '04',
      value: '哈哈'
    }, {
      key: '01',
      value: '乐乐'
    }];

    // 方法1:利用reduce方法遍历数组,reduce第一个参数是遍历需要执行的函数,第二个参数是item的初始值
    var obj = {};
    arr = arr.reduce(function (item, next) {
      obj[next.key] ? '' : obj[next.key] = true && item.push(next);
      return item;
    }, []);
    console.log(arr)

  

posted @ 2022-04-18 09:34  夏冬青  阅读(728)  评论(0编辑  收藏  举报