The syntax looks to be right off of MDN, so I'm not understanding why this object destructuring isn't working. The variables return undefined, why?
let obj={age: "3", name: "spike"};
let {a,b}=obj;//returns a and b as undefined, why?
When destructuring the objects, we use keys as the name of the variable. The variable name must match the property (or keys) name of the object. If it does not match, then it receives an undefined value. This is how JavaScript knows which property of the object we want to assign.
Use the logical OR operator to destructure from a nullable object in TypeScript, e.g. const { name, age } = obj || ({} as Person) . The logical OR operator is used to provide a fallback in case the object has a value of null or undefined .
You can use the object destructuring assignment to swap the values of two or more different variables. The snippet above used direct object destructuring to reassign the firstName and website variables with the values of the object literal on the right-hand side of the assignment operator.
You need to use name
and age
as the variables that you destructure from the object like so:
let obj={age: "3", name: "spike"};
let {age, name}=obj;
console.log(age);
console.log(name);
Alternatively, you can assign new names to the destructured variables by using the following syntax:
let obj={age: "3", name: "spike"};
let {age: a, name: b}=obj;
console.log(a);
console.log(b);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With