Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested object destructuring and renaming

Is it possible to rename a variable when destructuring a nested object in JavaScript? Consider the following code:

const obj = {a: 2, b: {c: 3}};
const {a: A, b:{c}} = obj;

How can I rename c in above code like I renamed a to A?

const {a: A, b:{c}: C} = obj

doesn't work.

like image 486
darKnight Avatar asked Nov 18 '17 17:11

darKnight


People also ask

Can we perform Destructuring on nested objects?

Gotchas of Nested Destructuring One thing we cannot do with nested destructuring is to destructure a null or undefined value. If we attempt to do so it will throw an error: So, if we want to use nested destructuring we must be certain that the nested structure exists, or intentionally catch the thrown error.

Can you Destructure array of objects?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.

Can you Destructure an object?

Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array​ at a time.

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 same way you set a new name for A - {c: C}:

const obj = {a: 2, b: {c: 3}};

const {a: A, b:{c: C}} = obj;

console.log(C);
like image 77
Ori Drori Avatar answered Oct 23 '22 14:10

Ori Drori