Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to push an object into in an existing object's property

Tags:

javascript

I want to append to this object:

var obj =
{
   "myKey":
   {
       "subkey": [1,2,3]
   }
};

this an object of additional subkeys I want to append to obj

var addKeys = {
   "subkey2" [3,4,5],
   "subkey3" [5,6,7]
}

I want to do something like obj.myKey.push(addKeys); but I know that's only for arrays. My final object should look ultimately like this:

var obj =
{
   "myKey":
   {
       "subkey": [1,2,3],
       "subkey2" [3,4,5],
       "subkey3" [5,6,7]
   }
};
like image 362
amigo21 Avatar asked Dec 11 '25 17:12

amigo21


1 Answers

 var obj =
{
   "myKey":
   {
       "subkey": [1,2,3]
   }
};

var addKeys = {
   "subkey2": [3,4,5],
   "subkey3": [5,6,7]
};
 
 Object.assign(obj.myKey, addKeys)
 
 console.log(obj);

Object.assign will overwrite the first argument. It is called a "destructive" operation. If you want to merge objects and return a new one:

 var obj =
{
   "myKey":
   {
       "subkey": [1,2,3]
   }
};

var addKeys = {
   "subkey2": [3,4,5],
   "subkey3": [5,6,7]
};
 
var merged = Object.assign({}, obj.myKey, addKeys)
 
 console.log(merged);
 console.log(obj);
like image 51
Joe Frambach Avatar answered Dec 13 '25 07:12

Joe Frambach