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.
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.
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.
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.
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.
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);
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