js数组对象根据id去重的四种方法

例如:想去除重复id为1的项

arr = [
  { id: 1, name: '张三', age: 20 },
  { id: 1, name: '张三', age: 20 },
  { id: 2, name: '李四', age: 20 },
  { id: 3, name: '马五', age: 20 }
];

方法一

通过forEach再通过some方法判断数组是否包含当前对象id,不包含则添加

some() {
  let some: any = [];
  this.arr.forEach(el => {
    if (!some.some(e => e.id == el.id)) {
      some.push(el);
    }
  });
  console.log(some);
}

方法二

通过forEach再通过find方法判断数组是否包含当前对象id,不包含则添加

find() {
  let find: any = [];
  this.arr.forEach(el => {
    if (!find.find(e => e.id == el.id)) {
      find.push(el);
    }
  });
  console.log(find);
}

方法三

通过reduce方法,通过定义的obj,判断obj[next.id] 是否存在,存在设置为“”,不存在则push

reduce() {
  let obj = {};
  let reduce = [];
  reduce = this.arr.reduce(function (item, next) {
    //item为没有重复id的数组,next为当前对象
    obj[next.id] ? '' : (obj[next.id] = true && item.push(next));
    return item;
  }, []);
  console.log(reduce);
}

方法四

通过for循环遍历,再通过some方法判断数组是否包含当前对象id,不包含则添加

forAway() {
  let forData = [];
  for (let i = 0; i < this.arr.length; i++) {
    if (!forData.some(e => e.id == this.arr[i].id)) forData.push(this.arr[i]);
  }
  console.log(forData);
}

猜你喜欢

转载自blog.csdn.net/m0_69429961/article/details/131166792