Rename Variable While Destructuring In Javascript

Stephen Charles Weiss on April 04, 2019

I recently came across a situation where I had two different props in a component that had the same name (they were in different parts of the objec... [Read Full]
markdown guide
 

There is a way to pick out sub-properties using desructuring,

but I think it's awful for readability..

const me = {
  name:'David',
  family: {
    wife : {
      name: 'TBD'
    },
    animal: {
      name : 'Jess',
      type: 'dog',
    },
  }
}


const { family: { wife: { name: wife } } } = me;
const { family: { animal: { name: dog } } } = me;

// OR

const { family } = me;

const { wife: { name: wife1 } } = family;
const { animal: { name: dog1 } } = family;

console.log({ wife1 });
console.log({ dog1 });
 

Ah, this is cool though!

If you want, you can do all three at once -- though I agree with your point that for readability, there aren't any gains here.

const { 
  name,
  family: { wife: {name: wife} } , 
  family : { animal : {name: dog } } 
  } = me;
 

Not much related, but sometimes I wish there is something like TypeScript import renaming in the Javascript which would allow this;

const { name1 as name2 } = someObject;
code of conduct - report abuse