Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

88
Views
Is there a simple way to merge two objects?

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.

7 months ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

7 months ago · Juan Pablo Isaza Report

0

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);

7 months ago · Juan Pablo Isaza Report

0

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);

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs