Combining two objects in JavaScript




One factor that I’ve to do quite usually when writing JavaScript code is to mix properties from two objects right into a single object.

For instance, given these two objects:

const a = {
  title: "John",
  age: 23
};
const b = {
  job: "Analyst"
};
Enter fullscreen mode

Exit fullscreen mode

…what could be accomplished to keep away from copying properties manually?

const c = {
  title: a.title,
  age: a.age,
  job: b.job
};
Enter fullscreen mode

Exit fullscreen mode



Answer 1: Object.assign

Object.assign is a built-in methodology launched to JavaScript as a part of the ES6 customary. It permits you to copy properties from a goal object to the supply object. A attainable answer to the above drawback could possibly be:

Object.assign(b, a);
Enter fullscreen mode

Exit fullscreen mode

This fashion b would have each its personal properties and a’s properties. Nonetheless, we’d wish to keep away from modifying b. In such case, we will introduce a brand new, empty object and replica properties from a and b to it.

const c = Object.assign({}, a, b);
Enter fullscreen mode

Exit fullscreen mode



Answer 2: lodash

If for some cause you can’t use ES6 language options in your utility, you possibly can resort to utilizing the lodash library.

const c = _.assign({}, a, b);
Enter fullscreen mode

Exit fullscreen mode



Answer 3: object unfold operator

One other ES6-based answer and my private favourite are to make use of the item unfold operator.

const c = { ...a, ...b };
Enter fullscreen mode

Exit fullscreen mode

The triple-dot operator unwraps an object and allows you to put its properties into a brand new object. By unwrapping each a and b and placing it into a brand new object ({}) we find yourself with an object having each a‘s and b‘s properties. So, which manner is one of the best ways? It will depend on your choice and necessities. Simply choose one and be constant in your alternative!



Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.


Checkout extra Articles on Sayed.CYou

#Combining #objects #JavaScript