Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isnt this object destructuring working?

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?
like image 943
what Avatar asked Nov 18 '17 23:11

what


People also ask

How do you Destructure an object in es6?

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.

How do you Destructure a null object?

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 .

Can I use object Destructuring?

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.


1 Answers

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);
like image 170
Christian Santos Avatar answered Nov 14 '22 22:11

Christian Santos