How to merge properties of two JavaScript Objects dynamically?

You can dynamically merge properties of JavaScript objects using one of two methods. These are

1) Object.assign()

The Object.assign() This method copies all properties from one or more source objects into a single target object. It will return the target object.

Example-1

<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 objects have the same key, the value of the object that appears later in the distribution will also be copied. This is what happens when keys have different values. __S.11__

Example-2

<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. This is most commonly used in variable arrays where multiple values are expected. JavaScript objects can be combined using a spread operator because they are key-value paired entities.

syntax

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

Example

<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"}