DEV Community

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

Posted on

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