How to merge properties of two JavaScript Objects dynamically?


There are two methods to merge properties of javascript objects dynamically. They are

1) Object.assign() 

The Object.assign() method is used to copy the values of all properties from one or more source objects to a target object. It will return the target object.

Example-1

 Live Demo

<html>
<body>
<script>
   var target = { a: "ram", b: "rahim" };
   var source = { c: "akbar", d: "anthony" };
   var returnedTarget = Object.assign(target, source);
   document.write(JSON.stringify(target));
   document.write(JSON.stringify(returnedTarget));
</script>
</body>
</html>

output

{"a":"ram","b":"rahim","c":"akbar","d":"anthony"}
{"a":"ram","b":"rahim","c":"akbar","d":"anthony"}


If the objects have the same keys, then the value of the key of the object which appears later in the distribution will be copied. The following example shows up the scenario when there are same keys with different values. 

Example-2

Live Demo

<html>
<body>
<script>
   var target = { a: "ram", b: "rahim" };
   var source = { b: "akbar", d: "anthony" };
   var returnedTarget = Object.assign(target, source);
   document.write(JSON.stringify(target));
   document.write("</br>");
   document.write(JSON.stringify(returnedTarget));
</script>
</body>
</html>

Output

{"a":"ram","b":"akbar","d":"anthony"}
{"a":"ram","b":"akbar","d":"anthony"}

2) Using spread operator

The spread operator allows an expression to be expanded in places where multiple elements/variables/arguments are expected. It is mostly used in a variable array where there is multiple values are expected. Since javascript objects are key value paired entities, we can merge them in to one using spread operator.

syntax

var target = [...obj1, ...obj2, ...]

Example

Live Demo

<html>
<body>
<script>
   var target = { a: "ram", b: "rahim" };
   var source = { b: "akbar", d: "anthony" };
   var returnedTarget = {...target, ...source}
   document.write(JSON.stringify(returnedTarget));
</script>
</body>
</html>

Output

{"a":"ram","b":"akbar","d":"anthony"}

Updated on: 30-Jul-2019

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements