Short and simple.
const bar = {
x: 5,
};
const { x: foo } = bar;
console.log(foo); // 5
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);
});
Top comments (2)
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).
You can find it on the official MDN site. It's under a section called Assigning to new variable names