Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object destructuring: how to use intermediate nested property

var { iWantThis: { andThis, andThisToo } } = x;

Is there a way to get access to all three in one destructuring call? I want to avoid two calls like so:

var { iWantThis } = x;
var { andThis, andThisToo } = iWantThis;
like image 367
Kelly Selden Avatar asked Oct 15 '15 01:10

Kelly Selden


People also ask

Can we perform Destructuring on nested objects?

Nested Object and Array DestructuringYou can destructure as deeply as you like: As you can see, keys a , b , and c are not implicitly defined, even though we pulled out nested values, firstElemOfC and remainingElementsOfC , from the array at c .

How do you Destructure a property?

The object destructuring is a useful JavaScript feature to extract properties from objects and bind them to variables. What's better, object destructuring can extract multiple properties in one statement, can access properties from nested objects, and can set a default value if the property doesn't exist.

How do you Destructure an object in typescript?

And this is destructuring an object. Let's take the following example: const user = { firstname: 'Chris', lastname: 'Bongers', age: 32 }; const { firstname, age } = user; By using this destructuring, we extract specific properties from an object.

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.


1 Answers

The closest I can come up with is:

var { iWantThis, iWantThis: { andThis, andThisToo } } = x;

Though I'd use let instead, if I'm using ES6 ;)

like image 181
locks Avatar answered Nov 09 '22 15:11

locks