且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将Javascript对象添加到另一个Javascript对象中

更新时间:2021-11-10 22:26:47

ES5

<script>
function mix(source, target) {
   for(var key in source) {
     if (source.hasOwnProperty(key)) {
        target[key] = source[key];
     }
   }

}

  mix(options, products);
</script>

ES6 - 这会改变objectToMergeTo

const combinedObject = Object.assign(objectToMergeTo, source1, source2)

ES7(带扩展运算符的语法美) -
但是这个版本创建了一个新实例,你无法添加到带有扩展运算符的对象中。

ES7 (syntax beauty with spread operator) - this version however creates a new instance, you can't add into an object with spread operator.

const combined = { ...source1, ...source2 }