有两种方法可以动态合并javascript对象的属性。他们是
Object.assign()方法被用于从一个或多个源对象的所有属性的值复制到目标对象。它将返回目标对象。
<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"}
如果对象具有相同的键,则将复制分发中稍后出现的对象的键值。下面的示例显示了当存在具有不同值的相同键时的情况。
<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"}
该价差运算符允许表达在多个元素/变量/参数预期的地方进行扩展。它主要用于需要多个值的变量数组中。由于javascript对象是键值配对的实体,因此我们可以使用传播运算符将它们合并为一个。
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"}