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

Discussion (0)