How to rename fields when using object destructuring

By

Learn how to rename a field while destructuring a JavaScript object, assigning a property to a new variable name with the colon syntax, as in firstName: name.

~~~

When you destructure an object, you can rename the extracted variable with a colon: write the property name, then :, then the new variable name.

const person = {
  firstName: 'Tom',
  lastName: 'Cruise'
}

const { firstName: name, lastName } = person

name //'Tom'
lastName //'Cruise'

Here firstName is extracted from the object, but stored in a variable called name. lastName keeps its original name.

Why would you rename a field?

Sometimes an object contains some set of properties, but you want to destructure it changing the names.

For example a property name does not suit your naming convention, or you already have a variable with that name in scope. Declaring const { firstName } = person when a firstName variable already exists throws an error, so renaming is the way out.

Watch the order

This syntax trips up a lot of people, me included. The property you’re reading is on the left of the colon. The new variable name is on the right.

If you write it backwards:

const { name: firstName } = person

firstName //undefined

JavaScript looks for a name property on person, doesn’t find one, and you get undefined. No error, no warning. If a renamed variable is mysteriously undefined, check the order first.

Combining renaming with default values

You can rename a field and give it a default value at the same time. The default kicks in when the property is missing:

const { middleName: middle = 'none' } = person

middle //'none'

Renaming nested properties

The same colon syntax works at any depth:

const artist = {
  name: 'Caravaggio',
  location: { city: 'Milan' }
}

const { location: { city: town } } = artist

town //'Milan'

Notice that this only creates the town variable. location itself is not declared, because we used it as a path to reach city, not as a variable.

Renaming in function parameters

Destructuring with renaming also works directly in a function signature. This is handy when a function receives an object and you want a shorter name inside:

const greet = ({ firstName: name }) => {
  console.log(`Hello ${name}`)
}

greet(person) //Hello Tom
~~~

Related posts about js: