javascript 如何将一个对象的元素推入另一个对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29949552/
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
How to push elements of an object into another object?
提问by Rana Mallah
Like in arrays we can add new elements by using array.push(item)
. How to do the same with objects
? And can it be done inside the object? Like:
就像在数组中一样,我们可以使用 array 添加新元素.push(item)
。如何做同样的事情objects
?并且可以在对象内部完成吗?喜欢:
var myObject={apple: "a", orange: "o"};
var anothObject = {lemon: "l", myObject};
采纳答案by Jonathan.Brink
You can use jQuery's extend function: http://api.jquery.com/jquery.extend/
您可以使用 jQuery 的扩展功能:http: //api.jquery.com/jquery.extend/
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
};
// Merge object2 into object1
$.extend( object1, object2 );
回答by vjdhama
You could add some properties of an object simply like this :
您可以像这样简单地添加对象的一些属性:
obj = {a : "1", b : "2"};
myObj = {c: "3", d : "4"};
myObj.a = obj.a;
myObj.b = obj.b;
Update:
更新:
In that case just do this :
在这种情况下,只需这样做:
for(var prop in obj) myObj[prop] = obj[prop];
And to filter out the unwanted properties inside the loop body you could also do this :
为了过滤掉循环体内不需要的属性,你也可以这样做:
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
myObj[prop] = obj[prop];
}
}
回答by xor
To copy all elements of one object to another object, use Object.assign
:
要将一个对象的所有元素复制到另一个对象,请使用Object.assign
:
var myObject = { apple: "a", orange: "o" };
var anothObject = Object.assign( { lemon: "l" }, myObject );
Or, more elegantly ES6 style using spread ...
operator:
或者,使用扩展...
运算符更优雅的 ES6 风格:
var myObject = { apple: "a", orange: "o" };
var anothObject = { lemon: "l", ...myObject };
Note however, that while I write this, this is still in proposal stage, although support is quite widespread (it works in my browser).
但是请注意,虽然我写这篇文章,但它仍处于提案阶段,尽管支持非常广泛(它在我的浏览器中有效)。
回答by Olivia O.
A non-jquery option: you could iterate of the keys of the object to be merged.
非 jquery 选项:您可以迭代要合并的对象的键。
var myObject={apple: "a", orange: "o"};
var anothObject = {lemon: "l"};
Object.keys(myObject).forEach(function(key) {
anothObject[key] = myObject[key];
});
At the end of the loop anothObject
is {lemon: "l", apple: "a", orange: "o"}
在循环的末尾anothObject
是{lemon: "l", apple: "a", orange: "o"}
回答by Trott
var myObject={apple: "a", orange: "o"};
myObject.lemon = 1; // myObject is now {apple: "a", orange: "o", lemon: 1}
回答by Adem ?lhan
You can use jQuery.extend()
function
您可以使用jQuery.extend()
功能
var myObject={apple: "a", orange: "o"};
var anothObject = {lemon: "l"};
jQuery.extend(myObject, anothObject);
console.log(myObject);