如何动态合并两个 JavaScript 对象的属性?
有两种方法可以动态合并 javascript 对象的属性。它们是
1) Object.assign()
Object.assign() 方法用于从一个或多个源对象复制所有属性的值到目标对象。它将返回目标对象。
示例-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>
输出
{"a":"ram","b":"rahim","c":"akbar","d":"anthony"} {"a":"ram","b":"rahim","c":"akbar","d":"anthony"}
如果对象具有相同的键,则将复制分布在后面的对象的键的值。以下示例显示了出现具有不同值的相同键时的场景。
示例-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>
输出
{"a":"ram","b":"akbar","d":"anthony"} {"a":"ram","b":"akbar","d":"anthony"}
2) 使用扩展运算符
扩展运算符允许在期望有多个元素/变量/参数的地方扩展表达式。它主要用于在期望出现多个值的变量数组中。由于 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"}
广告