将Javascript对象添加到另一个Javascript对象中 [英] Add Javascript Object into another Javascript Object
本文介绍了将Javascript对象添加到另一个Javascript对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定
options = {
underscored: true
}
products = {
foo: bar
}
我想要得到
products = {
underscored: true
foo: bar
}
是否可以在Javascript中将对象推送到另一个对象?
Is it possible to push an object into another object in Javascript?
推荐答案
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 }
这篇关于将Javascript对象添加到另一个Javascript对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文