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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9843884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:00:55  来源:igfitidea点击:

Add Javascript Object into another Javascript Object

javascript

提问by lemon

Given

给定的

options = {
 underscored: true
}

products = {
 foo: bar
}

I'd like to get

我想得到

products = {
 underscored: true
 foo: bar
}

Is it possible to push an object into another object in Javascript?

是否可以在 Javascript 中将一个对象推送到另一个对象中?

回答by Peter Aron Zentai

ES5

ES5

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

}

  mix(options, products);
</script>

ES6 - this will mutate objectToMergeTo

ES6 - 这将改变 objectToMergeTo

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

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

ES7(带有扩展运算符的语法之美)-但是此版本创建了一个新实例,您不能使用扩展运算符将其添加到对象中。

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

回答by Elliot Bonneville

You could do this:

你可以这样做:

for(var key in options) {
    products[key] = options[key];
}

That would effectively combine the two objects' variables.

这将有效地结合两个对象的变量。

回答by Mark Schultheiss

var options = {
    underscored: true
};
var products = {
    foo: 'bar'
};
products.underscored = options.underscored;
alert(products.underscored+":"+products.foo);

put quotes around the 'bar' to make it actually have a value, semi-colons and var on the objects, but you get the point.

在 'bar' 周围加上引号,使其实际上在对象上具有值、分号和 var,但您明白了。

EDIT: also worth noting;

编辑:也值得注意;

products.options = options;
alert(products.options.underscored);//alerts true

回答by Biswajit Chatterjee

you can use jquery.extend(products,options). jQuery.extend combines two objects, over rides the matching element values in the target object and returns resulting object. For more info :http://api.jquery.com/jquery.extend/

您可以使用 jquery.extend(products,options)。jQuery.extend 组合两个对象,覆盖目标对象中的匹配元素值并返回结果对象。欲了解更多信息:http: //api.jquery.com/jquery.extend/