There are two methods to merge properties of javascript objects dynamically. They are
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.
<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>
{"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.
<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>
{"a":"ram","b":"akbar","d":"anthony"} {"a":"ram","b":"akbar","d":"anthony"}
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.
var target = [...obj1, ...obj2, ...]
<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>
{"a":"ram","b":"akbar","d":"anthony"}