How to Rename Variables When Destructuring an Object in JavaScript?

The destructuring assignment syntax unpacks properties from objects into distinct variables, which by default, have the same name as the property keys. Luckily, renaming these variables is possible and fairly straightforward, and in this article we'll see how it can be done.

Destructuring and Renaming Variables

Let's suppose you have the following object:

const obj = { hello: 'world' };

To rename hello into, let's say foo, it would look like the following:

const { hello: foo } = obj;

console.log(foo); // 'world'
console.log(hello); // Uncaught ReferenceError: hello is not defined

Destructuring and Renaming a Variable Multiple Times

It is also possible to destructure the same property multiple times into different variable names, for example:

const { hello: foo, hello: bar } = obj;

console.log(foo); // 'world'
console.log(bar); // 'world'

Destructuring Deep Nested Property Into a Different Variable Name

Let's suppose we have an object like this:

const obj = { foo: { bar: 'baz' } };

If you wanted to destructure and rename the deep nested object property bar into, let's say qux, you could do it like so:

const { foo: { bar: qux } } = obj;

console.log(qux); // 'baz'
console.log(foo); // Uncaught ReferenceError: foo is not defined

Since it is possible to rename the same object property into different variable names, we could rename the deep nested property, as well as the parent, like so:

const { foo: { bar: qux }, foo: waldo } = obj;

console.log(qux); // 'baz'
console.log(waldo); // { bar: 'baz' }

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.