js对象数组去重

两种方式

// 使用数组方法reduce去重
var obj = {};
var aa = [{
    "name": "aa",
    "pwd": "xvxv"
}, {
    "name": "aa",
    "pwd": "xvxv"
}, {
    "name": "bb",
    "pwd": "xvxv"
}, {
    "name": "cc",
    "pwd": "xvxv"
}];
 
aa = aa.reduce(function(item, next) {
    obj[next.name] ? '' : obj[next.name] = true && item.push(next);
    return item;
}, []);
console.log(aa);

// 判断对象中是否存在key
var result = [];
var obj = {};
for(var i =0; i<aa.length; i++){
  if(!obj[aa[i].key]){
     result.push(aa[i]);
     obj[aa[i].key] = true;
  }
}
console.log(result); 

// 纯数组去重
var arr = [1,2,3,1,2,3,4];
var arr_later = [];
arr.forEach((item,index)=>{
  if(index == arr.indexOf(item)){
     arr_later.push(item);
  }
)
console.log(arr_later);
posted @ 2020-06-17 09:45  海常7号  阅读(263)  评论(0编辑  收藏  举报