Basic destructuring
Destructuring an object into separated variables is a built-in feature of javascript. Here is an example:
const dog = {
name: 'MAX',
breed: 'German Shepherd'
};
/**
* Variables names must match object properties names.
* Order is not important.
*/
const { name, breed } = dog;
console.log(name); // MAX
console.log(breed); // German Shepherd
Assignment separate from declaration
But what if you need to destructure an object into preexistent variables? Well, it’s a little bit tricky but this is how you do it:
const dog = {
name: 'MAX',
breed: 'German Shepherd'
};
let name, breed;
// if some condition is satisfied
if (true) {
/**
* without the parentheses (...), javascript will interpret the left-hand side of the expression as a block and not an object literal.
* also precede the expression with a semicolon ";", otherwise it may be used to execute a function on the previous line.
*/
;({ name, breed } = dog)
}
console.log(name); // MAX
console.log(breed); // German Shepherd
A simpler way
This is a simpler way without all the hassles of the parentheses and semicolons:
const dog = {
name: 'MAX',
breed: 'German Shepherd'
};
let name, breed;
if (true) {
const {} = { name, breed } = dog;
}
console.log(name); // MAX
console.log(breed); // German Shepherd
Which method do you prefer? It’s up to you.