我不知道如何做到这一点,所以任何帮助将不胜感激。我有两个想要组合成一个对象的对象。我已经使用了扩展运算符来执行此操作:
newObj = {...obj1, ...obj2};
这个,例如给我这个:
{
[
obj1A{
"item": "stuff",
"item": "stuff"
},
obj1B{
"item": "stuff",
"item": "stuff"
}
],
[
obj2A{
"item": "stuff",
"item": "stuff"
},
obj2B{
"item": "stuff",
"item": "stuff"
}
]
}
但我想要的是:
{
[
obj1A{
"item": "stuff",
"item": "stuff"
},
obj1B{
"item": "stuff",
"item": "stuff"
},
obj2A{
"item": "stuff",
"item": "stuff"
},
obj2B{
"item": "stuff",
"item": "stuff"
}
]
}
任何人都知道怎么做?
答案 0 :(得分:4)
使用正确的唯一名称,您可以使用Object.assign
并创建新对象。
var object1 = { obj1A: { item1: "stuff", item2: "stuff" }, obj1B: { item1: "stuff", item2: "stuff" } },
object2 = { obj2A: { item1: "stuff", item2: "stuff" }, obj2B: { item1: "stuff", item2: "stuff" } },
combined = Object.assign({}, object1, object2);
console.log(combined);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)
如果你正在使用jQuery,你可以做类似于https://jsfiddle.net/d11kfd4d/的事情:
var a = {
propertyOne: 'One',
propertyTwo: 'Two'
};
var b = {
propertyThree: 'Three',
propertyFour: 'Four'
}
var c = $.extend(a, b);
console.log(c);
答案 2 :(得分:0)
假设你有一个拼写错误(将此[]
更改为此{}
)并且键是valids(不重复),则可以使用Spread语法。
var obj1 = { obj1A: { item: "stuff", item2: "stuff" }, obj1B: { item: "stuff", item2: "stuff" } },
obj2 = { obj2A: { item: "stuff", item2: "stuff" }, obj2B: { item: "stuff", item2: "stuff" } }
console.log({...obj1, ...obj2});
.as-console-wrapper { max-height: 100% !important; top: 0; }