I want to combine the content of multiple objects that have the same key with that key as the property in JavaScript.
Objects:
const cat1 = { med1: { a: 10, b: 12 }, med2: { c: 14, d: 16 } };
const cat2 = { med1: { e: 18, f: 20 }, med2: { g: 22, h: 24 } };
Expected output:
{
med1: { a: 10, b: 12, e: 18, f: 20 },
med2: { c: 14, d: 16, g: 22, h: 24 }
}
I have tried to use both object spreading and Object.assign with no sucess. With object spreading, since objects have no iterator this is returning an error. Object.assign would work however since the two objects to combine have the same key, the second object is overwriting the first.
CodePudding user response:
const cat1 = { med1: { a: 10, b: 12 }, med2: { c: 14, d: 16 } };
const cat2 = { med1: { e: 18, f: 20 }, med2: { g: 22, h: 24 } };
const result = Object.keys(cat1).map(k => { k: {return {...cat1[k], ...cat2[k]}}});
console.log(result);
CodePudding user response:
const merge = (...objects) =>
objects.reduce((p, c) => copyObjToTarget(c, p), {})
function copyObjToTarget(o, t={}) {
for (let[name,val] of Object.entries(o)) {
t[name] = isPrimitive(val) ? val : copyObjToTarget(val, t[name])
}
return t
}
// Assumes no functions.
function isPrimitive(val) {
return val === null || typeof val !== 'object'
}
const o1 = { med1: { a: 10, b: 12 }, med2: { c: 14, d: 16 } }
const o2 = { med1: { e: 18, f: 20 }, med2: { g: 22, h: 24 } }
console.log(JSON.stringify(merge(o1, o2), null, 2))