Reputation: 137
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 item in obj.cats (Simba)
How can I add to the obj.cats
here? All solutions I try they override cats
Wanted result:
obj {
cats : {
{'name': 'Milo', 'age': 3},
{'name': 'Simba', 'age': 2}
}
}
Upvotes: 0
Views: 66
Reputation: 68933
Your wanted result is not valid, you can try with the object key:
var obj = {}
obj.cats = {1:{'name': 'Milo', 'age': 3}} // first item
Object.assign(obj.cats, {2:{'name': 'Simba', 'age': 2}}) // add new item to obj.cats
console.log(obj) // result one item in obj.cats (Simba)
Upvotes: 1
Reputation: 56754
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.cats
console.log(obj) // result two items in obj.cats (Milo & Simba)
Upvotes: 3