Igor Simic
3 years ago

How to add new key/value to a JavaScript object?

How to add new element to Javascript object? In this article we will show you simple way to add key/value pair to Javascript object by using spread operator where you can add new object element in just one line. Here is how:

So, let's say we have a object which contains online users:
let onlineUsers = {
  1421:{ // user id
    name: "foo"  // user name
And now we want to add new user to this object, 
first let's create new object:
let newUser = {
  1439:{ // user id
    name: "bar"  // user name
and now we can simply add new element to object by using spread operator:
onlineUsers = {...onlineUsers, ...newUser};
and now your object should look like this:
    name: "foo" 
    name: "bar"

Here is another example, how to add just one new key/value to existing object element. Here is example of the object:
let user = {

and now we want to add property lastName to existing user, we will take existing object and just add new key with value to it:
user = {...user,'lastName':'testoso'};
and now our object looks like this:
  name: "tester", 
  role: "user", 
  lastName: "testoso"

and that is it.
happy coding