14

My question is simple, I have 2 objects like this:

object1 = {
    content1: {}
}

object2 = {
    stuff: {},
    moreStuff: {}
}

And I want to add the content of object2 to content1 (which is inside of object1).

Like this:

object1 = {
    content1: {
        stuff: {},
        moreStuff: {}
    }
}

5 Answers 5

20

This is very simple;

object1.content1 = object2

Sign up to request clarification or add additional context in comments.

Comments

10

This will allow you to add an object inside another object.
With other examples you will get a substitution instead of adding. 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);

Now if you need something more advance, you should take a look to some functional programming framework like ramda, which will allow you to merge object. R.merge.

Comments

3

Something keeping you from doing: object1.content1 = object2 ?

Comments

3

Try this

object1.content1 = object2;

Comments

3

Initialization

var object1 = {
   content1:"1"
}
var object2 = {
   content2:"2",
   content3:"3"
}

Put contents of object2 into object1's content1

object1.content1 = object2;//this is the code you are looking for


console.log(object2);

You are done!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.