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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const user = { name: "John", age: 45, } user.city = "New York"; console.log(user) // output : {name: "John", age: 45, city: "New York"} user["address"] = "8th Avenue"; console.log(user); // output : {name: "John", age: 45, city: "New York", address: "8th Avenue"} |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const user = { name: "John", age: 45, } const newUser = { ...user, city: "New York", address: "8th Avenue" } console.log(newUser); // output : {name: "John", age: 45, city: "New York", address: "8th Avenue"} |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
const target = { a: 1, b: 2 }; const returnedTarget = Object.assign(target, {c:3}); console.log(target); // output : { a: 1, b: 2, c: 3 } console.log(returnedTarget) // output : { a: 1, b: 2, c: 3 } |
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.