DEV Community

Stephen Charles Weiss
Stephen Charles Weiss

Posted on • Originally published at stephencharlesweiss.com on

Rename Variable While Destructuring In Javascript

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

I wanted to use both and compare them, but also wanted to use destructuring so I didn’t have to drill through the object to find them.

This got me wondering whether or not I’d be able to simply rename while destructuring the object.

Turns out you can.

Imagine the following:

const me = {
  name:'stephen',
  family: {
    wife : {
      name: 'kate'
    },
    animal: {
      name : 'finn',
      type: 'dog',
    },
  }
}

So, I want to be able to access my name, my wife’s name, and my dog’s name.

I can do that with destructuring, like so:

const { name } = me
const { name: wife } = me.family.wife
const { name: dog } = me.family.dog

The only thing that I really wish this could do that it can’t is allow additional restructuring within the object and combine this into one line. That is, the following will not work:const {name, family.wife.name: wife, family.dog.name: dog} = me

Oh well.

Wes Bos has a helpful post on the topic. Check it out.

Top comments (3)

Collapse
 
vidhill profile image
David Hill

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 });
Collapse
 
stephencweiss profile image
Stephen Charles Weiss

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;
Collapse
 
stojakovic99 profile image
Nikola Stojaković

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;