我有两个数组,我想合并两个数组,但数组1与2合并并创建新数组,新数组中也有array1和array2数据,但没有重复的条目。
我尝试使用concat函数,但没有用
数组1:
[[id: 45,
name: Tv,
active: false,
], [id: 56,
name: Car,
active: true,
][id: 60,
name: bus,
active: false,
]]
数组2:
[[id: 45,
company: sony,
size: 32,
price: 451
],
[id: 56,
company: suzuki,
size: L,
price: 3000
]]
我想要这样的数据:
[[id: 45,
name: tv,
active: false,
company: sony,
size: 32,
price: 451
],
[id: 56,
name: car,
active: true,
company: suzuki,
size: M,
price: 3000
],
id: 60,
name: bus,
active: false]]
但是如果您要使用此数据在javascript中的对象中创建对象
答案 0 :(得分:1)
您可以使用以下方法来合并任意数量的数组:
const arr1 = [{ id: 45, name: "Tv", active: false }, { id: 56, name: "Car", active: true }, {id: 60, name: "bus", active: false }];
const arr2 = [{ id: 45, company: "sony", size: 32, price: 451 }, { id: 56, company: "suzuki", size: "L", price:3000 }];
const arr3 = [{ id: 45, type: 'electronics' }];
const mergeArrays = (...arrays) => {
const all = [].concat.apply([], arrays);
const ids = new Set(all.map(item => item.id));
return Array.from(ids).map(id =>
Object.assign({}, ...all.filter(item => item.id === id))
);
};
console.log(mergeArrays(arr1, arr2, arr3));
答案 1 :(得分:0)
您可以使用reduce
形成一个新的对象数组。在迭代元素时,您可以使用find
从另一个数组中获取具有相同id
的对象。我们通过解构合并当前对象和数组2中的对象。
var ar1 = [{id:45,name:"Tv",active:!1,},{id:56,name:"Car",active:!0},{id:60,name:"bus",active:!1}],
ar2 = [{id:45,company:"sony",size:32,price:451},{id:56,company:"suzuki",size:"L",price:3000}];
let res = ar1.reduce((a,c) => {
let tmp = ar2.find(({id}) => id == c.id);
tmp ? a.push({...c, ...tmp}) : a.push(c);
return a;
},[])
console.log(res)
单线:
let res = ar1.reduce((a,c) => (a.push({...c, ...ar2.find(({id}) => id == c.id)}),a),[])