Destructure and Rename Variables on Objects in JavaScript

Destructuring is a powerful way to unpack values from arrays or properties from objects into variables.

If you aren't sure what destructuring is, check out this introduction article first.

Sometimes we have data come back from an API call with weird names or semantics that don't conform to our codebase.

Here's a straightforward way to rename these variables while destructuring.

Renaming Variables

To rename a variable, you can use the syntax:

const { oldName: newName } = object;

In this example, we rename oldName to newName.

Let's look at a full usage example of creating and renaming an object property:

const person = { name: 'Niall Maher', age: 31 };
const { name: fullName } = person;
console.log(fullName); // Output: Niall Maher

In the above example, we take the name value from person and rename it to fullName.

I hope this tip helped! ❤️

Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.