0
Why wonât my object destructure?
https://code.sololearn.com/WsC4XdNWw2LT/?ref=app Iâm trying to destructure an object and assign variables to the properties values. But when I console.log the variable it just returns null and Iâm not sure why. Any help or tips would be greatly appreciated
1 Answer
0
/*
Object destructuring works with this scheme : { property_name: variable_name }, wich could be shorthanded { name } if you want to use same 'name' for the variable to assign and the property name... And you could assign more than once variable/property:
*/
var my_object = {
property1: 42,
property2: 'forty-two',
property3: [1,2,3]
};
var { property3: myvar1, property2: myvar2 } = my_object;
console.log(myvar1+''); // 1,2,3
console.log(myvar2); // forty-two
/*
Also, if you want to assign an already declared variable, you should enclose the assignement in round parenthesis:
*/
var myvar3;
({ property1: myvar3 } = my_object);
console.log(myvar3); // 42