我的问题很简单,我有两个这样的对象:
object1 = {
content1: {}
}
object2 = {
stuff: {},
moreStuff: {}
}
我想将 object2 的内容添加到 content1 (在 object1 中)。
像这样:
object1 = {
content1: {
stuff: {},
moreStuff: {}
}
}
答案 0 :(得分:9)
这很简单;
object1.content1 = object2
答案 1 :(得分:7)
这将允许您在另一个对象中添加对象 使用其他示例,您将获得替换,而不是添加。 e.g。
const obj1 = {
innerObj:{
name:'Bob'
},
innerOBj2:{
color:'blue'
}
}
const obj2 = {
lastName:'Some',
age:45
}
obj1.innerObj = Object.assign(obj1.innerObj,obj2);
console.log(obj1);

现在,如果你需要更高级的东西,你应该看看像 ramda 这样的函数式编程框架,这将允许你合并对象。的 R.merge 即可。
答案 2 :(得分:3)
阻止你做的事:object1.content1 = object2
?
答案 3 :(得分:3)
试试这个
object1.content1 = object2;
答案 4 :(得分:3)
初始化
var object1 = {
content1:"1"
}
var object2 = {
content2:"2",
content3:"3"
}
将object2的内容放入object1的content1
object1.content1 = object2;//this is the code you are looking for
console.log(object2);
你完成了!