Search code examples
javascriptarraysobject-literal

How can I push new values to a JavaScript object array


I have an object with a property that contains an array, I was wondering what the best way of inserting into that array, this is the object:

const object1 = 
  {"users": [{"username":"john","email":"john@gmail.com","id":"john_2011221"}, 
  {"username":"steve","email":"steve@gmail.com","id":"steve_201193841"}]};

I want to make the object like this:

const object1 = 
      {"users": [{"username":"john","email":"john@gmail.com","id":"john_2011221"}, 
      {"username":"steve","email":"steve@gmail.com","id":"steve_201193841"}
      {"username":"Emily","email":"emily@gmail.com","id":"emily_20119567"}]};

Solution

  • Access the array inside the Object using object1["users"]. Then you can simply push your new object into this array like this

    const object1 = 
      {"users": [{"username":"john","email":"john@gmail.com","id":"john_2011221"}, 
      {"username":"steve","email":"steve@gmail.com","id":"steve_201193841"}]};
    
    object1["users"].push({"username":"Emily","email":"emily@gmail.com","id":"emily_20119567"})