I have two arrays and each of them has objects. How best can I simplify adding two objects into one but in a new list. e.g
a = [{a:1, b:2, c:3}, {d:1, e:4, f:2}]
b = [{m:1, n:2, o:4}, {r:1,s:3,u:5}, {k:1,j:4,f:8}]
z = [{a:1, b:2, c:3, m:1, n:2, o:4}, {d:1, e:4, f:2, r:1,s:3,u:5}, {k:1,j:4,f:8}]
Suppose you have list a and b, I want to add the objects of each position together in list z.
You could merge the two object in this way:
let a = [{a:1, b:2, c:3}, {d:1, e:4, f:2}]
let b = [{m:1, n:2, o:4}, {r:1,s:3,u:5}, {k:1,j:4,f:8}]
let z = [];
b.forEach((x, i) => {
let merged = {...x, ...a[i]};
z.push(merged)
})
console.log(z);
I'd go over the maximum length of a and b and use Object.assign to copy the values. Assuming you want a generic solution to any two arrays, where either can be longer than the other, note that you need to check the lengths as you go:
z = [];
for (let i = 0; i < Math.max(a.length, b.length); ++i) {
const result = i < a.length ? a[i] : {};
Object.assign(result, i < b.length ? b[i] : {});
z.push(result);
}
Try this :
const a = [{a:1, b:2, c:3}, {d:1, e:4, f:2}];
const b = [{m:1, n:2, o:4}, {r:1,s:3,u:5}, {k:1,j:4,f:8}];
let c = [];
if(a.length > b.length){
c = a.map((e,i) => {
return {
...e,
...b[i]
}
});
}else{
c = b.map((e,i) => {
return {
...e,
...a[i]
}
});
}
console.log(c);