js如何处理两个json数组去除重复数据,然后合并数组

转载:https://zhidao.baidu.com/question/1643525236454533140.html

如:

var a = [
{
"id":"1001",
"name":"张三",
"age":"18",
"address":"北京市朝阳区",
"school":"朝阳区第二中学"
},
{
"id":"1002",
"name":"李四",
"age":"15",
"address":"北京市海淀区",
"school":"海淀区第二中学"
},
{
"id":"1003",
"name":"王五",
"age":"16",
"address":"北京市石景山区",
"school":"石景山区第二中学"
}
];
var b = [
{
"id":"1004",
"name":"小毛",
"age":"18",
"address":"北京市朝阳区",
"school":"朝阳区第二中学"
},
{
"id":"1003",
"name":"王五",
"age":"16",
"address":"北京市石景山区",
"school":"石景山区第二中学"
}
]
去重后结果:
var c = [
{
"id":"1001",
"name":"张三",
"age":"18",
"address":"北京市朝阳区",
"school":"朝阳区第二中学"
},
{
"id":"1002",
"name":"李四",
"age":"15",
"address":"北京市海淀区",
"school":"海淀区第二中学"
},
{
"id":"1003",
"name":"王五",
"age":"16",
"address":"北京市石景山区",
"school":"石景山区第二中学"
},
{
"id":"1004",
"name":"小毛",
"age":"18",
"address":"北京市朝阳区",
"school":"朝阳区第二中学"
}

];

var  c = a.concat(b), //合并成一个数组
         temp = {}, //用于id判断重复
         result = []; //最后的新数组
     //遍历c数组,将每个item.id在temp中是否存在值做判断, 
     c.map((item,index)=>{
         if (!temp[item.id]){
             result.push(item);
             temp[item.id] =  true
         }
     })
     console.log(result)    


JS的数组去除重复。

//去除重复。
let _selectedIds2=[]; //最后的新数组;
_selectedIds.map((item)=>{ //从这里开始匹配,如果没有匹配到,
   if(_selectedIds2.indexOf(item)<0){ _selectedIds2.push(item);}
})



你可能感兴趣的:(js,json)