How to 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 object1 ).

Like this:

object1 = {
    content1 = {
        stuff = {
        },
        moreStuff = {
        }
    }
}
+4
source share
5 answers

It is very simple;

object1.content1 = object2

+4
source

This will allow you to add an object inside another object.
In other examples, you will get a replacement instead of adding . eg.

const obj1 = {
	innerObj:{
  	name:'Bob'
  },
  innerOBj2:{
  	color:'blue'
  }
}

const obj2 = {
	lastName:'Some',
  age:45
}

obj1.innerObj = Object.assign(obj1.innerObj,obj2);
console.log(obj1);
Run code

, - , , ramda, . R.merge.

+4

Something does not allow you to do object1.content1 = object2:?

+2
source

try it

object1.content1 = object2;
+2
source

Initialization

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

Put the contents of object2 to object1 content1

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


console.log(object2);

You are done!

+2
source

Source: https://habr.com/ru/post/1670015/


All Articles