Destructuring and rename property

JavascriptObjectEcmascript 6RenameDestructuring

Javascript Problem Overview


const a = {
 b: {
  c: 'Hi!'
 }
};

const { b: { c } } = a;

Is it possible rename b in this case? I want get c and also rename b.

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleusroxView Question on Stackoverflow
Solution 1 - JavascriptNina ScholzView Answer on Stackoverflow
Solution 2 - JavascriptBergiView Answer on Stackoverflow