JavaScript Destructuring: Renaming AND Nesting

While addressing some linter issues today, I couldn’t figure out how to destructure from a JavaScript object while:

  1. Renaming a field and
  2. Destructuring nested fields from that same field

Renaming, I could do. Nested fields, no problem. But to do both, for the same field? Googling got me nowhere — I found examples aplenty for doing one or the other, often in the same post. Examples of how to rename a field. Examples of how to destructure nested fields. But nothing for the syntax for how to do both to the same field.

What does this mean? Suppose, for example, I have the following JavaScript object:

const person = {
  name: 'Rob',
  spouse: {
    name: 'Sherry'
  }
}

Using destructuring, I could rename the spouse field to, say, wife, by specifying fieldName : newName, like this:

const { spouse: wife } = person
// wife === { name: 'Sherry' }

Also, I could access the name field of spouse, like this:

const { spouse: { name } } = person
// name === 'Sherry'

What if, however, I wanted to both? What if I wanted to rename spouse to wife and destructure the nested name? I tried sprinkling colons anywhere I could think of, to no avail. Finally, in a spot of, “I’m sure this is wrong, but might as well try it,” I found the answer. As it turns out, to do both, you, well, do both:

const { spouse: wife, spouse: { name } } = person
// wife === { name: 'Sherry' }, name === 'Sherry'

The linter errors are gone, and I feel enlightened.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.