Skip to content Skip to sidebar Skip to footer

Add New Object To Another Object's Object

var obj = {} obj.cats = {'name': 'Milo', 'age': 3} // first item Object.assign(obj.cats, {'name': 'Simba', 'age': 2}) // add new item to obj.cats console.log(obj) // result one

Solution 1:

You can use an array of objects:

var obj = {}

obj.cats = [{name: 'Milo', age: 3}] // first item

obj.cats.push({name: 'Simba', age: 2}) // add new item to obj.catsconsole.log(obj) // result two items in obj.cats (Milo & Simba)

Solution 2:

Your wanted result is not valid, you can try with the object key:

var obj = {}

obj.cats = {1:{'name': 'Milo', 'age': 3}} // first itemObject.assign(obj.cats, {2:{'name': 'Simba', 'age': 2}}) // add new item to obj.catsconsole.log(obj) // result one item in obj.cats (Simba)

Post a Comment for "Add New Object To Another Object's Object"