Let's say I have two objects.
obj1 = {
a: 1,
b: 3,
c: 1
}
obj2 = {
a: 3,
b: 1,
c: 3
}
And I would like to add these two. In a way that each key value add them together with the corresponding one. So obj3 = obj1 obj2 would result in:
obj3 = {
a: 4,
b: 4,
c: 4
}
Is there a simpler way of doing this without manually adding each key value pair like
obj3.a = obj1.a obj2.a
CodePudding user response:
This is something that could be done very simply through the use of Array.prototype.reduce()
if you were able to store these objects as an array:
const myObjects = [
{
a: 1,
b: 3,
c: 1,
},
{
a: 3,
b: 1,
c: 3,
},
];
const output = myObjects.reduce((prev, curr) => ({
a: prev.a curr.a,
b: prev.b curr.b,
c: prev.c curr.c,
}));
CodePudding user response:
This function sum property's object (dynamic property)
function objSumProperty(obj1, obj2) {
const data = {};
Object.keys(obj1).map((k) => (data[k] = obj1[k] (obj2[k] || 0)));
return data;
}
CodePudding user response:
Use parameters rest (...
) to collect all objects to an array. Create an array of all entries ([key, value]
pairs) using Array.flatMap()
with Object.entries()
. Reduce the array of entries to a single object.
This function allows you to combine all keys from 2 or more objects, even if the objects have different keys.
const fn = (...objs) => objs
.flatMap(Object.entries)
.reduce((acc, [key, value]) => ({
...acc,
[key]: (acc[key] ?? 0) value
}), {})
const obj1 = {"a":1,"b":3,"c":1}
const obj2 = {"a":3,"b":1,"c":3}
console.log(fn(obj1, obj2)) // combining 2 objects
const obj3 = {"a":10,"d":15,"e":20}
console.log(fn(obj1, obj2, obj3)) // combining 3 objects