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 = a.concat(b); //合并数组 var temp = {}; //存放id var result = []; //新数组 c.map((item,index) => { if(!temp[item.id]){ result.push(item); temp[item.id] = true; } }) document.getElementById('txt').innerHTML = JSON.stringify(result)
有两个json数组demo1和demo2 var demo1 = [{"id": 0, "name": "牛肉"},{"id": 1,"name": "羊肉"}]; var demo2 = [{"id": 2, "name": "牛肉"},{"id": 3,"name": "鱼肉"},{ "id": 4,"name":"鸡肉"}]; 数组合并 var totalDemo = demo1.concat(demo2); console.log(totalDemo); //[{"id": 0, "name": "牛肉"},{"id": 1,"name": "羊肉"},{"id": 2, "name": "牛肉"},{"id": 3,"name": "鱼肉"},{ "id": 4,"name":"鸡肉"}] 数组合并用的是concat方法,它可以用于字符串之间的连接和数组之间的连接。 数组去重 上面已经得到合并的数组 totalDemo ,去掉name属性是一样的json对象 var temp = {}; //用于name判断重复 var result = []; //最后的新数组 totalDemo.map(function (item, index) { if(!temp[item.name]){ result.push(item); temp[item.name] = true; } }); console.log(result);//[{"id": 0, "name": "牛肉"},{"id": 1,"name": "羊肉"},{"id": 3,"name": "鱼肉"},{ "id": 4,"name":"鸡肉"}]; map方法:按照原始数组元素顺序依次处理元素。可以在map方法里面输入console.log(item)打印看下,它会把数组中的对象依次打印出来。