Javascript add property to object
- Authors
- Name
- Hamza Rahman
- Published on
- -3 mins read
Let us see three ways in javascript to add a property to an object. We will also see how we can use some of the methods to dynamically create the property key as well.
These methods are the dot notation, square bracket notation, and using the spread operator.
You can also update already created properties with these methods instead of adding them.
Method 1: Dot notation
One of the simplest method to add properties to object is the dot notation. The only downside for using this method is that you already need to know the property key before adding it, this way doesn't allow dynamic addition of the property key.
let game = { name: 'Rust', releaseYear: '2013',}
console.log(game)//Adding propertygame.steamRating = 9
console.log(game)
Output:
{name: 'Rust', releaseYear: '2013'}//After adding property{name: 'Rust', releaseYear: '2013', steamRating: 9}
Method 2: Square bracket notation
This method allows you to create new properties normally or with the additional advantage that the property key can also be passed on dynamically from a variable besides the value.
let game = { name: 'Rust', releaseYear: '2013',}
let newProperty = 'genre'let genreList = ['Survival game', 'First-person shooter', 'Multiplayer']
console.log(game)//Adding propertygame['steamRating'] = 9//Adding property name and value dynamicallygame[newProperty] = genreList
console.log(game)
Output:
{name: 'Rust', releaseYear: '2013'}//After adding properties{ name: 'Rust', releaseYear: '2013', steamRating: 9, genre: ['Survival game', 'First-person shooter', 'Multiplayer']}
Method 3: Spread operator
Spread operator allows us to destructure objects and utilizing that we can create a new object with the additional property we want to create. The advantage of this method is that it creates a shallow copy of the original object for us and also allows dynamic keys for the object.
let game = { name: 'Rust', releaseYear: '2013',}
let newProperty = 'genre'let genreList = ['Survival game', 'First-person shooter', 'Multiplayer']
console.log(game)//Adding propertieslet updatedGameObject = { ...game, steamRating: 9, [newProperty]: genreList }
console.log(updatedGameObject)
Output:
{name: 'Rust', releaseYear: '2013'}//After adding properties{ name: 'Rust', releaseYear: '2013', steamRating: 9, genre: ['Survival game', 'First-person shooter', 'Multiplayer']}
Conclusion
These are some of the ways to add properties to objects, they all have different advantages ranging from simplicity to dynamic key values and creating shallow object copies.
Hopefully, you find different usage for all these methods in your coding journey 🚀.