Reputation: 285
lets say i have:
object1 = {
atk: 3,
def: 6,
hp: 4,
level: 17,
};
object2 = {
atk: 1,
def: 4,
hp: 2,
level: 10,
};
i want to multiply the two objects so i end up with
object3 = {
atk: 3, // 1 * 3
def: 24, // 4 * 6
hp: 8, // 2 * 4
level: 170, // 17 * 10
};
i tried like this
let obj3 = {};
obj3.atk = object1.atk * object2.atk;
obj3.def= object1.def * object2.def;
//etc....
but not sure if there's some simpler way since there are more keys/values than I've listed here.
Upvotes: 0
Views: 76
Reputation: 21160
One of the simplest (code complexity) solutions would probably be using a simple for...in
loop, iterating over the keys of the fist object.
const object1 = { atk: 3, def: 6, hp: 4, level: 17 };
const object2 = { atk: 1, def: 4, hp: 2, level: 10 };
const obj3 = {};
for (const key in object1) {
obj3[key] = object1[key] * object2[key];
}
console.log(obj3);
This does assume that object1
and object2
both have the same keys.
Upvotes: 1
Reputation: 604
I would create a helper function that does pretty much the same as the previous answers:
const multiplyObjectsByKeys = (a, b) => Object.keys(a).reduce((acc, key) => ({ ...acc, [key]: a[key] * b[key] }), {})
const object3 = multiplyObjectsByKeys(object1, object2)
In case you are using lodash in your project, you could also do it like this:
_.assignWith(object1, object2, (a, b) => a * b)
Upvotes: 1
Reputation: 2293
I guess the most elegant way to do it is using the reduce
array method, mixed with the Object.keys()
function, which returns an array containing the keys of the object:
const object1 = { atk: 3, def: 6, hp: 4, level: 17, };
const object2 = { atk: 1, def: 4, hp: 2, level: 10 };
const object3 = Object.keys(object1).reduce((result, key) => {
result[key] = object1[key] * object2[key];
return result;
}, {});
console.log(object3);
Upvotes: 1
Reputation: 66228
You can use a combination of Object.entries
to unpack a source object (e.g. object1
), and the map through it to multiple its values with the corresponding value obtained by using key
as an accessor on object2
.
Once that is done it is a matter of using Object.fromEntries
to convert the [key, value]
tuples back into an object:
const object1 = {
atk: 3,
def: 6,
hp: 4,
level: 17,
};
const object2 = {
atk: 1,
def: 4,
hp: 2,
level: 10,
};
const object3 = Object.fromEntries(Object.entries(object1).map(([key, value]) => {
value *= object2[key];
return [key, value];
}));
console.log(object3);
Upvotes: 1