W3docs

How to Merge Properties of Two JavaScript Objects Dynamically

Have you ever wanted to merge the properties of two objects in JavaScript dynamically? This tutorial is aimed at showing you how to do it in rational ways.

In the given tutorial, we are going to show you some fast-solutions to merging the properties of two objects dynamically in JavaScript.

Solution 1 . Spread Operator

The first solution considers using the spread operator. It helps an iterable to expand in places where 0+ arguments are expected. Mostly you can use it in the variable or array, in which more than one value is expected. With the help of it, the code obtains a list of parameters from an array.

Objects in JavaScript are key-value paired dictionaries. So, different objects can be merged into one applying the spread (…) operator.

The spread syntax looks as follows:

javascript

const object1 = { ...object2, ...object3 };

Let’s take a look at an example:

javascript

javascript— editable

In the second example, let’s suppose that the objects obtain the same key. In such a scenario, it is required to use the value of the key of the object appearing later in the spread order.

It is demonstrated here:

javascript

javascript— editable

Solution 2. Object.assign()

As an alternative solution, you can use the Object.assign() method. As a rule, this method is applied for copying the values of all properties from a single or more source objects to a target object. As a consequence, the target object will be returned.

The first example is the following:

javascript

javascript— editable

Its output will look like this:

{"a":"object","b":"array","c":"js","d":"w3docs"}
{"a":"object","b":"array","c":"js","d":"w3docs"}

Also, in this case, the value of the key of the object appearing later in the spread order will be copied. In our following example, you can notice that there are the same keys with different values.

The second example is the following:

javascript

javascript— editable

And its output is here:

{"a":"object","b":"js","d":"w3docs"}
{"a":"object","b":"js","d":"w3docs"}

Solution 3. jQuery

jQuery also offers a rational solution to this issue.

You can merge objects using the code below:

javascript

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
  </head>
  <body>
    <div id="div"></div>
    <script>
      let obj1 = {
        banana: {
          weight: 25,
          price: 200
        },
        cherry: 97
      };
      let obj2 = {
        banana: {
          price: 100
        },
        durian: 800
      };
      // Merge obj2 into obj1
      $.extend(obj1, obj2);
      // Assuming JSON.stringify
      $("#div").append(JSON.stringify(obj1));
    </script>
  </body>
</html>