Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an object inside another object in Javascript?

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: {}
    }
}
like image 590
Diogo Capela Avatar asked Feb 17 '17 04:02

Diogo Capela


3 Answers

This is very simple;

object1.content1 = object2

like image 83
buræquete Avatar answered Nov 13 '22 23:11

buræquete


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.

like image 44
Hosar Avatar answered Nov 14 '22 00:11

Hosar


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

like image 3
Kelvin De Moya Avatar answered Nov 14 '22 00:11

Kelvin De Moya