Destructuring and rename property
28,970
Solution 1
You could destructure with a renaming and take the same property for destructuring.
const a = { b: { c: 'Hi!' } };
const { b: formerB, b: { c } } = a;
console.log(formerB)
console.log(c);
Solution 2
You can destructure the same property multiple times, onto different targets:
const { b: {c}, b: d } = a;
This assigns a.b.c
to c
and a.b
to d
.
Author by
leusrox
Updated on July 17, 2020Comments
-
leusrox almost 4 years
const a = { b: { c: 'Hi!' } }; const { b: { c } } = a;
Is it possible rename
b
in this case? I want getc
and also renameb
. -
leusrox almost 5 yearsThank you, I didn't know that the property can be repeated in destructuring.
-
leusrox almost 5 yearsThanks, your answer is also correct, but @NinaScholz answered a little earlier.
-
RegarBoy almost 4 yearsbut you cannot do this while destructuring arrays can you?
-
Nina Scholz almost 4 years@RegarBoy, do you have an example?
-
RegarBoy almost 4 years@NinaScholz Sure, stackoverflow.com/questions/63307361/… In between I remember you Nina, you have helped me with array maps 5 years ago. Thank you :D
-
VimNing almost 3 yearsI like this one, more concise.