JavaScript对象值去重的方法

var arr = [{
   key: '01',
   value: '乐乐'
  }, {
   key: '02',
   value: '博博'
  }, {
   key: '03',
   value: '淘淘'
  },{
   key: '04',
   value: '哈哈'
  },{
   key: '01',
   value: '乐乐'
  }];
  // 方法1:利用对象访问属性的方法,判断对象中是否存在key
  var result = [];
  var obj = {};
  for(var i =0; i<arr.length; i++){
   if(!obj[arr[i].key]){
     result.push(arr[i]);
     obj[arr[i].key] = true;
   }
  }
  console.log(result); // [{key: "01", value: "乐乐"},{key: "02", value: "博博"},{key: "03", value: "淘淘"},{key: "04", value: "哈哈"}]
  // 方法2:利用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); // [{key: "01", value: "乐乐"},{key: "02", value: "博博"},{key: "03", value: "淘淘"},{key: "04", value: "哈哈"}]

JavaScript数组中删除指定对象

let test = [
      {
        name: "Mike",
        incentives: "23.45",
        id: "1"
      },
      {
        name: "Larsen",
        incentives: "34.78",
        id: "2"
      },
      {
        name: "Steve",
        incentives: "26.78",
        id: "3"
      }
    ];
 //方法一
  let test1 = test.filter(obj => obj.id !== "2");
 //方法二
 test.splice(
      //find the index of the element to be removed
      test.indexOf(
        test.find(function(element) {
          return element.id === "2";
        })
      ),
      //remove 1 element from the index found
      1
    );
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐