// 將一個JSON數組[{},{},{}]按一定規則合併到另一個JSON數組[{},{},{}] // Object.assign方法的第一個參數是目標對象,後面的參數都是源對象。 var list1 = [{id:2,name:'aa'},{id:4,name:'bb'},{id:1,name: ...
// 將一個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: "男"}]