2 Ways to Append Values to an Object in JavaScript

Appending values to an Object is a quite common situation when working objects in javascript. You might need to add a single value or multiple values to an object. This article explains 2 different ways to append values to an object using javascript.

Method 1: Appending a New Value Directly to an Object

You can append a new value to an object directly in 2 different ways. Here is an example that appends a new value to an object with different syntaxes.

In the above example, the city key with value is inserted with . syntax and the address is added with [key] syntax.

Method 2: Using Object Destructuring to Append a New Value

You can use object destructuring syntax or object.assign() to append a new value to an object. You can also merge 2 different objects if you have 2 objects. The example using object destructuring is given below.

Please note this method will create a new object and wouldn’t change the original object. Only use this method if you don’t want to mutate the original object.

You can also use object.assign() method to add a new value to an object. The following example adds a new key and value to the object.

The object.assign() returns a new object and also modifies the target object as you can see in the example above.

Conclusion

There are 2 ways to append a value to an object in JavaScript. The first method is to add value directly to the object with . or using [key] syntax. The second method is to use the object destructuring or object.assign() method. The second method is recommended if you want to create a new object.

Latest articles

Related articles