将一个JSON数组[{},{},{}]按一定规则合并到另一个JSON数组[{},{},{}]

2019-01-02 21:08发布

// 将一个JSON数组[{},{},{}]按一定规则合并到另一个JSON数组[{},{},{}]
// Object.assign方法的第一个参数是目标对象,后面的参数都是源对象。
var list1 = [{id:2,name:'aa'},{id:4,name:'bb'},{id:1,name:'cc'}];
var list2 = [{id:2,age:10,sex:'男'},{id:1,age:18,sex:'男'},{id:4,age:16,sex:'女'}];
var arr = [];
var list = list1.map((item1)=> {
  arr = list2.filter((item2)=>{
    return item2.id == item1.id;
  });
  console.log(arr);
  console.log( Object.assign(item1,arr[0]) );
  return Object.assign(item1,arr[0] );
});
console.log(list1);// [ {id: 2,name: "aa",age: 10,sex: "男"},{id: 4,name: "bb",age: 16,sex: "女"},{id: 1,name: "cc",age: 18,sex: "男"}]
console.log(list);// [ {id: 2,name: "aa",age: 10,sex: "男"},{id: 4,name: "bb",age: 16,sex: "女"},{id: 1,name: "cc",age: 18,sex: "男"}]

// index索引一一对应
var list3 = [{id:2,name:'aa'},{id:4,name:'bb'},{id:1,name:'cc'}];
var list4 = [{id:2,age:10,sex:'男'},{id:4,age:16,sex:'女'},{id:1,age:18,sex:'男'}];
var list5 = list3.map((item1,index) => {
  // 如果希望合并后返回一个新对象,可以改写上面函数,对一个空对象合并。
  console.log( Object.assign({},item1,list4[index]) );
  return Object.assign({},item1,list4[index] );
});
console.log(list3);//[{id:2,name:'aa'},{id:4,name:'bb'},{id:1,name:'cc'}]
console.log(list5);// [ {id: 2,name: "aa",age: 10,sex: "男"},{id: 4,name: "bb",age: 16,sex: "女"},{id: 1,name: "cc",age: 18,sex: "男"}]

文章来源: https://www.cnblogs.com/jianglibaizhi/p/10185490.html
标签: