DEV Community

Raúl Sánchez
Raúl Sánchez

Posted on

8 1

Destructuring with an alias

Short and simple.

 const bar = {
    x: 5,
 };

 const { x: foo } = bar;
 console.log(foo); // 5
Enter fullscreen mode Exit fullscreen mode

This can be useful when you need to destructure a value that has a similar or same name as an existing variable. E.g.,

const cars = [{
   car: true,
   van: false,
   make: 'Honda',
   year: 2001,
   color: 'Red',
}, {
   car: true,
   van: false,
   make: 'Nissan',
   year: 2000,
   color: 'Blue',
}];

cars.map(car => {
   const { car: isCar } = car;
   console.log(isCar);
});
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
pdina profile image
Paolo E Basta

This is very nice and works well. I just wonder where this alias stuff is officially documented, because I found anything (except some post on StackOverflow but without any official reference).

Collapse
 
rsanchezp profile image
Raúl Sánchez

You can find it on the official MDN site. It's under a section called Assigning to new variable names

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️