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! ❤️