A blog for technology, SEO tips, website development and open source programming.

Rename & Destructure Javascript Variables ES6

0 870

On the last post we have looked at a dead simple introduction to what destructuring actually is and how to destructuring JavaScript Objects. This post will look another case scenario which would be Rename & Destructure Javascript Variables ES6 at the same time.




Sometimes data comes back in some odd names, and you might not necessarily want to use a property key as the end variable name. Maybe you don’t like that variable name or it’s already taken in your scope.

const facebook = 'facebook.com';
const profile = {
  first: 'Panayiotis',
  last: 'Georgiou',
  links: {
    social: {
      twitter: 'https://twitter.com/panay_georgiou',
      facebook: 'https://facebook.com/panayiotisgeorgiou.net',
    },
    web: {
      cv: 'https://www.panayiotisgeorgiou.com'
      blog: 'http://www.panayiotisgeorgiou.net'
    }
  }
};

On the above example, I have already used facebook as a variable.

What happens next ?

For sure I can’t use it again, but I’m stuck, why?

Because this object gives me Facebook as a key and this object gives me Facebook as a key.

What you can do about this?

You can rename them as you destructure the objects

So – I want the facebook property, but I want to call it fb.

const { facebook: fb } = profile.links.social;

The above code will pull the profile.links.social.facebook into a variable called fb.

That’s it for now.

If you liked this article, then please subscribe to my YouTube Channel for video tutorials.

You can also find me on Twitter and Facebook.

[alert type=white ]

Don’t miss out ..

Destructuring JavaScript Objects

Arrow Functions for Beginners Javascript

[/alert]

Leave a Reply

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More