0
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}
 }
}
4
  • 3
    Are you trying to make an array? Commented Dec 11, 2019 at 0:29
  • 3
    An object has to have unique keys, so they will be overridden with the newer ones, what is your expected/wanted output? Commented Dec 11, 2019 at 0:30
  • are you saying that I have to add an array somewhere in the obj? I edited the question with what I want. Thx Commented Dec 11, 2019 at 0:35
  • 3
    Your expected result is not a valid Javascript data structure. You have two values in the obj.cats object, but no keys. Objects are collections of key-value-pairs, where the keys must be unique per-object. Commented Dec 11, 2019 at 0:35

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.