DEV Community

loading...
Cover image for Object Destructuring with ES6

Object Destructuring with ES6

toddster79 profile image Todd Carlson Updated on ・2 min read

This week I am focusing on object destructuring with ES6. I was first introduced to object destructuring while a student at the Flatiron School during our module on React. Object destructuring is something I use almost daily, especially as a React developer, and I would like to take this opportunity to share how it works with you. So, without further ado, let's dive in.

Destructuring JavaScript objects is similar to destructuring JavaScript arrays. It allows us to pull multiple values at a time, and to store each of those values inside their own variable. To fully appreciate how useful this is, I think it might be helpful to look at the old way of pulling values from objects and assigning them to their own variables. Let's say we have an object that contains these key/value pairs:

const dog = {
  name: 'Doug',
  age: 4,
  breed: 'Pug',
  temperament: 'friendly'
};
const name = dog.name;
const breed = dog.breed;

Depending on how large the object is, this could get really old really fast. Thanks to ES6 destructuring we can create multiple variables from the information contained inside of an object on a single line. To create the name and breed variables from our dog object we simple write this statement:

const { name, breed } = dog;

You can also assign a default value to the variable when the property of an object doesn’t exist. For example:

const dog = {
  name: 'Doug',
  breed: 'Pug',
  temperament: 'friendly'
};

const { name, age = 'unknown', breed } = dog

Since there is no age key/value pair inside the dog object, were we to log age to the console we would get back the string, "unknown".

In my opinion, the true power and usefulness of object destructuring is made apparent when you have to deal with the kind of nested data that you get back from a JSON API.

const dog = {
  name: 'Doug',
  breed: 'Pug',
  age: 4,
  temperament: 'friendly',
  links: {
    social: {
      twitter: 'https://twitter.com/dougthepug',
      instagram: 'https://instagram.com/realdougthepug',
    },
    web: {
      blog: 'https://dougthepug.com'
    }
  }
};

Let's say that we only want to grab the social media links from this nested object. To achieve this with destructuring we simply write:

const { twitter, instagram } = dog.links.social;

The url for each account is now stored inside the variables twitter, and instagram. Again destructuring is super useful if you are a front-end developer.

I hope this has been useful. I plan to dive more deeply into JavaScript objects in future posts.

Happy coding!

Discussion

pic
Editor guide