Categories
JavaScript Answers

How to Append a Property to a JavaScript Object?

Spread the love

Oftentimes, we want to append new properties to a JavaScript object in our code.

In this article, we’ll look at how to append a property to a JavaScript object.

Use the Object.assign Method

One way to append a property to a JavaScript object is to use the Object.assign method.

For instance, we can write:

const obj = {  
  foo: 1,  
  bar: 2  
}  
const newObj = Object.assign({}, obj, {  
  baz: 3  
})  
console.log(newObj)

We have an obj that we want to to add the baz property into it.

To do that, we call Object.assign with an empty object, obj and an object with the baz property.

Then all the properties from the objects in the 2nd and 3rd arguments are put into the empty object and returned.

Therefore, newObj is:

{  
  "foo": 1,  
  "bar": 2,  
  "baz": 3  
}

Use the Spread Operator

Another way to add a property into an object is to use the spread operator.

For instance, we can write:

const obj = {  
  foo: 1,  
  bar: 2  
}  
const newObj = {  
  ...obj,  
  baz: 3  
}  
console.log(newObj)

We spread the properties of obj into newObj .

And then we put the baz property after that.

Therefore, newObj is:

{  
  "foo": 1,  
  "bar": 2,  
  "baz": 3  
}

Conclusion

We can use the Object.assign method or the spread operator to append a property to an object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *