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.

Share:
28,970
leusrox
Author by

leusrox

Updated on July 17, 2020

Comments

  • leusrox
    leusrox almost 4 years
    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.

  • leusrox
    leusrox almost 5 years
    Thank you, I didn't know that the property can be repeated in destructuring.
  • leusrox
    leusrox almost 5 years
    Thanks, your answer is also correct, but @NinaScholz answered a little earlier.
  • RegarBoy
    RegarBoy almost 4 years
    but you cannot do this while destructuring arrays can you?
  • Nina Scholz
    Nina Scholz almost 4 years
    @RegarBoy, do you have an example?
  • RegarBoy
    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
    VimNing almost 3 years
    I like this one, more concise.