DEV Community

gavgrif
gavgrif

Posted on

Object destructuring for the newbie

Many of you will know this - but its something I have been using a lot lately and find to be very useful. so I thought I would share...

ES6 has introduced a new way of declaring variables from objects

consider this object:

    const merchant = {
      firstName: 'John',
      lastName: 'Smith',
      vendorAssignedID: '123456'
    };
Enter fullscreen mode Exit fullscreen mode

You could access these as:

  const firstName = merchant.firstName; // would assign a variable (firstName) to have the value of "John";
  const lastName = merchant.lastName; // would assign a variable (lastName) to have the value of "Smith";
  const vendorAssignedID = merchant.vendorAssignedID; // would assign a variable (vendorAssignedID) to have the value of "12345";
Enter fullscreen mode Exit fullscreen mode

This causes repetition of the property name and is very verbose - that’s where the object destructuring syntax is useful: you can read a property and assign its value to a variable without duplicating the property name. More than that, you can read multiple properties from the same object in just one statement!

To refactor the above script and apply the object destructuring to access the properties names :

  const {  firstName, lastName, vendorAssignedID  } = merchant;

    console.log(firstName); // 'John'
    console.log(lastName); // 'Smith'
    console.log(vendorAssignedID); // '123456'
Enter fullscreen mode Exit fullscreen mode

This statement defines the variables and assigns to them the values of the matching properties of the object.

You can alias the variables if the property name is too long for easy use

  const { firstName, lastName, vendorAssignedID: ID } = merchant;

    console.log(firstName); // 'John'
    console.log(lastName); // 'Smith'
    console.log(ID); // '123456'
Enter fullscreen mode Exit fullscreen mode

You can add a default value if the property name does not exist in the object

  const { firstName, lastName, vendorAssignedID: ID = '123456' } = merchant;

    console.log(firstName); // 'John'
    console.log(lastName); // 'GRiffith'
    console.log(ID); // '123456'
Enter fullscreen mode Exit fullscreen mode

There is much more to discuss with what you can do with object destructuring - here are some links from a quick google search

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
https://dmitripavlutin.com/javascript-object-destructuring/
https://javascript.info/destructuring-assignment
https://codeburst.io/es6-destructuring-the-complete-guide-7f842d08b98f
https://www.javascripttutorial.net/es6/javascript-object-destructuring/

Top comments (0)