Javascript add property to object

Authors
  • avatar
    Name
    Hamza Rahman
Published on
-
4 mins read
-

There are several ways in JavaScript to add a property to an object. This post covers dot notation, square bracket notation, the spread operator, and Object.assign, then shows how to add keys dynamically, add a property only when a condition is met, add to nested objects, and do it in TypeScript.

All of these also work for updating an existing property, not just adding a new one.

Method 1: Dot notation

The simplest way to add a property is dot notation. The one limitation is that you need to know the property name ahead of time, so it cannot be a dynamic key.

let game = {
name: 'Rust',
releaseYear: '2013',
}
game.steamRating = 9
console.log(game)

Output:

{ name: 'Rust', releaseYear: '2013', steamRating: 9 }

Method 2: Square bracket notation

Square brackets work like dot notation but let you pass the property name from a variable, so the key can be dynamic.

let game = {
name: 'Rust',
releaseYear: '2013',
}
let newProperty = 'genre'
let genreList = ['Survival game', 'First-person shooter', 'Multiplayer']
game['steamRating'] = 9
game[newProperty] = genreList // dynamic key from a variable
console.log(game)

Output:

{
name: 'Rust',
releaseYear: '2013',
steamRating: 9,
genre: ['Survival game', 'First-person shooter', 'Multiplayer']
}

Method 3: Spread operator

The spread operator creates a new object with the extra property instead of changing the original. That gives you a shallow copy, which is useful when you do not want to mutate the source object (React state, for example). It also supports dynamic keys with computed property syntax.

let game = {
name: 'Rust',
releaseYear: '2013',
}
let newProperty = 'genre'
let genreList = ['Survival game', 'First-person shooter', 'Multiplayer']
let updatedGame = { ...game, steamRating: 9, [newProperty]: genreList }
console.log(updatedGame)

Output:

{
name: 'Rust',
releaseYear: '2013',
steamRating: 9,
genre: ['Survival game', 'First-person shooter', 'Multiplayer']
}

Method 4: Object.assign

Object.assign copies properties from one or more source objects into a target. Use an empty object as the target to get a copy, like the spread operator. Use the original object as the target to mutate it in place.

let game = {
name: 'Rust',
releaseYear: '2013',
}
// copy into a new object
let copy = Object.assign({}, game, { steamRating: 9 })
// or mutate the original
Object.assign(game, { steamRating: 9 })

Adding several properties at once

Both the spread operator and Object.assign take more than one property, so you can add a batch in a single step.

let game = { name: 'Rust' }
let updated = { ...game, releaseYear: '2013', steamRating: 9, multiplayer: true }

Conditionally adding a property

Sometimes you only want to add a property when a value exists. Spread a short-circuit expression: when the condition is false it spreads an empty object and adds nothing.

let isOnSale = true
let discount = 25
let game = {
name: 'Rust',
...(isOnSale && { discount }),
}
// game is { name: 'Rust', discount: 25 }
// if isOnSale were false, game would just be { name: 'Rust' }

Adding to a nested object

To add a property deeper in the object, spread the parent level so you do not lose its other keys.

let game = {
name: 'Rust',
details: { releaseYear: '2013' },
}
let updated = {
...game,
details: { ...game.details, steamRating: 9 },
}
// updated.details is { releaseYear: '2013', steamRating: 9 }

Adding a property in TypeScript

TypeScript objects are typed, so you cannot add a property the type does not declare. Define the property up front (optional with ? if it may be missing), and assignment works the same way.

interface Game {
name: string
releaseYear: string
steamRating?: number // optional
}
const game: Game = { name: 'Rust', releaseYear: '2013' }
game.steamRating = 9 // allowed because it is declared
// For a flexible shape, use an index signature:
interface FlexibleGame {
name: string
[key: string]: unknown
}
const g: FlexibleGame = { name: 'Rust' }
g.anything = 'is allowed'

Conclusion

Dot and bracket notation mutate the object directly, while the spread operator and Object.assign give you a copy. Reach for bracket notation or computed keys when the property name is dynamic, the spread short-circuit trick when a property is conditional, and an interface or index signature when you are in TypeScript.