Objects act a bit different in JavaScript than other programming languages. This results in both pros and cons for its uses. For instance, there are multiple ways to update property values in a JavaScript object.
Example 1: Update property values individually
You can update each of the property value by accessing the object’s key directly as follows. Here I’m updating the favoriteColor property of the object.
const someObject = {
id: 1,
name: 'Gautam',
age: 27,
nationality: 'Indian',
favoriteColor: 'Purple',
}
someObject.favoriteColor = 'Blue'
// OR
// someObject['favoriteColor'] = 'Blue'
console.log(someObject)
Code language: JavaScript (javascript)
The result of the above code would be:
{
id: 1,
name: 'Gautam',
age: 27,
nationality: 'Indian',
favoriteColor: 'Blue'
}
Code language: CSS (css)
Similarly, you can update other properties as well.
Example 2: Update multiple properties with spread operator
You can update multiple properties at once without affecting the existing ones as follows:
let someObject = {
id: 1,
name: 'Gautam',
age: 27,
nationality: 'Indian',
favoriteColor: 'Purple',
}
someObject = { ...someObject, id: 2, favoriteColor: 'Red' }
console.log(someObject)
Code language: JavaScript (javascript)
With the above code, id and favoriteColor will get updated. The result of the above code would be:
{
id: 2,
name: 'Gautam',
age: 27,
nationality: 'Indian',
favoriteColor: 'Red'
}
Code language: CSS (css)
Please note that I’ve declared someObject object with a let keyword instead of const, as compared to Example 1. This is because on line 9, someObject is being re-initialized altogether with the old values as well as the new updated values.
Example 3: Update multiple properties on the old object with a new object
Of course, you can update parts of an existing object by merging it with a new object as follows:
let someObject = {
id: 1,
name: 'Gautam',
age: 27,
nationality: 'Indian',
favoriteColor: 'Purple',
}
const newObject = {
id: 2,
name: 'Gautam',
nationality: 'Indian',
favoriteColor: 'Green',
}
someObject = { ...someObject, ...newObject }
console.log(someObject)
Code language: JavaScript (javascript)
If you notice in the code above, age property is missing in the newObject object. Also, I’ve updated the favoriteColor to ‘Green’ in the newObject. The resultant object would have a combination (union) of both the objects:
{
id: 2,
name: 'Gautam',
age: 27,
nationality: 'Indian',
favoriteColor: 'Green'
}
Code language: CSS (css)
If you have any doubts please let me know in the comments below!