From JavaScript object or array to variables with destructuring assignment

OpenJavaScript 0

Last updated: September 27, 2022.

Destructuring assignment is the process of extracting data from a JavaScript object or array and storing it in variables. It can also optionally involve creating an object or array containing the non-destructured data.

This process can be done very efficiently using the ES6 destructuring assignment method.

In this tutorial, we will first look at object destructuring and then array destructuring. Though similar for both, ES6 destructuring assignment differs in important ways for objects and arrays.

Object destructuring assigment

Basic object destructuring

We are often faced with the challenge of working with an object that looks something like this (e.g. after making an API request and parsing the response):

const newsStory = {
   title: "Batman strikes again",
   trailingHeadline: "Gotham city again asks the question: hero or villan?",
   thumbnail: "http://www.somenewswebsite.com/story48849/thumbnail.jpeg",
   storyURL: "http://www.somenewswebsite.com/story48849",
   author: "Joe Bloggs",
   properties: {
      type: "story",
      premiumContent: true,
      storyId: 48849,
   }
}

And we often want to extract the contained data and store it in variables, so it is easier to work with.

The ‘long way’ to do this is to use dot notation to access each property value we are interested in and store in a variable:

/* The long way using dot notation ❌ */
const title = newsStory.title;
const trailingHeadline = newsStory.trailingHeadline;
const thumbnail = newsStory.thumbnail;
const storyURL = newsStory.storyURL;
const author = newsStory.author;
const type = newsStory.properties.type
const id = newsStory.properties.storyId;

This does the job but violates the DRY principle (‘don’t repeat yourself’). Since ES6 (2015), there is a more efficient way to do this. The syntax for ES6 object destructuring assignment is as follows:

const = { <property key list separated by commas> } = myObject

So at first it looks like we are going to declare a variable, but in the variable name position we list the keys of the properties we want to extract from the object inside brackets. Then, in the variable value position, we ‘feed in’ the object we want to destructure.

If the object has nested properties (as is the case in our example), we can access it is the comma-separated list in the following way: property: {nestedProperties}.

Applying this to our example now:

/* Using ES6 object destructuring ✔️ */
const { title, trailingHeadline, thumbnail, storyURL, author, properties: {type, storyId} } = newsStory;

console.log(title, trailingHeadline, thumbnail, storyURL, author, type, storyId);
// "Batman strikes again","Gotham city again asks the question: hero or villan?",
// "http://www.somenewswebsite.com/story48849/thumbnail.jpeg",
// "http://www.somenewswebsite.com/story48849",
// "Joe Bloggs", "story", 48849, 

In a single line of code, we have now achieved what took seven lines of code using the dot notation method!

Assigning new variable names

Want the names of variables to differ from their object key names? No problem!

This can be done using the following syntax within the destructuring assignment: keyInObject: newVariableName.

So, applied to our example:

const { title: articleTitle, trailingHeadline: articleHeadline, thumbnail: articleThumbnail, author: articleAuthor, 
properties: {type: articleType, storyId: articleId}} = newsStory;
 
console.log(articleTitle, articleHeadline, articleThumbnail, articleAuthor, articleType, articleId);
// "Batman strikes again","Gotham city again asks the question: hero or villan?",
// "http://www.somenewswebsite.com/story48849/thumbnail.jpeg",
// "http://www.somenewswebsite.com/story48849",
// "Joe Bloggs", "story", 48849, 

The output is the same as in the previous example, but we have now set new names for the variables.

Set a default variable value

It can often be a good idea to set a default value for a variable in case it is not found in the object when destrurcturing.

We set a default value using the following syntax for a variable inside the destructuring assignment: variableName = defaultValue.

Let's now slightly modify the object we were working with previously by removing the author property and set a default value for it in our object destructuring assignment.

const newsStory = {
   title: "Batman strikes again",
   trailingHeadline: "Gotham city again asks the question: hero or villan?",
   thumbnail: "http://www.somenewswebsite.com/story48849/thumbnail.jpeg",
   storyURL: "http://www.somenewswebsite.com/story48849",
   properties: {
      type: "story",
      premiumContent: true,
      storyId: 48849,
   }
}

const { title: articleTitle, trailingHeadline: articleHeadline, thumbnail: articleThumbnail, author: articleAuthor = "Captain anonymous", 
properties: {type: articleType, storyId: articleId}} = newsStory;
 
console.log(articleAuthor); // "Captain anonymous"

Now "Captain anonymous" is the value of articleAuthor.

Notice that we provided a new variable name for the author property (articleAuhor) and set a default value for it. The syntax used is keyInObject: newVariableName = defaultValue.

Storing non-destructured properties in a new object ✨🔮

Now it's time for the ES6 party trick that would be a nightmare using dot notation: you can create a new object in which the destructured objects no longer exist (because they have been 'removed' into variables).

For this, we use the spread operator (...) inside the object destructuring assignment, followed by the name we want to give to the new object. By convention, this is rest:

const newsStory = {
   title: "Batman strikes again",
   trailingHeadline: "Gotham city again asks the question: hero or villan?",
   thumbnail: "http://www.somenewswebsite.com/story48849/thumbnail.jpeg",
   storyURL: "http://www.somenewswebsite.com/story48849",
   properties: {
      type: "story",
      premiumContent: true,
      storyId: 48849,
   }
}

const { title: articleTitle, trailingHeadline: articleHeadline, ...rest} = newsStory;
 
console.log(rest);
// {
//     "thumbnail": "http://www.somenewswebsite.com/story48849/thumbnail.jpeg",
//     "storyURL": "http://www.somenewswebsite.com/story48849",
//     "properties": {
//         "type": "story",
//         "premiumContent": true,
//         "storyId": 48849
//     }
// }

We now have a new object called rest that is the original object without the destructured properties.

Array destructuring assignment

Basic array destructuring

To destructure an array, the following syntax is used:

const [ <new variable names separated by commas> ] = myArray

We feed in the array in the variable value position. And we list the names of the new variables inside the square brackets. Each variable corresponds to an element in the array we feed in.

For example:

const superheroes = ["Batman", "Spiderman", "Iron man"];

const [hero1, hero2, hero3] = superheroes;
console.log(hero1,hero2,hero3);
// "Batman", "Spiderman", "Iron man"

If there are fewer variables names inside square brackets than array elements, the remaining elements are simply ignored:

const superheroes = ["Batman", "Spiderman", "Iron man"];

const [hero1, hero2, hero3] = superheroes;
console.log(hero1,hero2);
// "Batman", "Spiderman"

Destructuring nested array elements

If there is nesting in the array, the destructuring assignment should mirror its structure:

const superheroes = [["Batman", "Christian Bale"], ["Spiderman", "Tom Holland"], ["Iron man", "Hugh Jackman"]];

const [ [hero1, actor1], [hero2,actor2], [hero3,actor3] ] = superheroes;

console.log(hero1,actor1,hero2,actor2,hero3,actor3);
// Batman, Christian Bale, Spiderman, Tom Holland, Iron man, Hugh Jackman

Setting default values

If an array element specified in the destructuring assignment is not found in the array passed in, setting a default value avoids its value being set to undefined:

const superheroes = ["Batman", "Spiderman", "Iron man"];

const [hero1, hero2, hero3, hero4="Anonymous Hero", hero5] = superheroes;
console.log(hero4);
// "Anonymous Hero"
console.log(hero5);
// Undefined

Skipping an array element

An array element can be skipped by simply leaving it blank in the destructuring assignment:

const superheroes = ["Batman", "Spiderman", "Iron man"];

const [hero1, , hero2] = superheroes;
console.log(hero1, hero2);
// Batman, Iron man

Creating a new array for non-destructured elements 🔥

And now for the cherry on the cake: ES6 array destructuring assignment allow you to use the spread operator (...) followed by a variable name to create a new array of remaining, non-destructured elements.

const superheroes = ["Batman", "Spiderman", "Iron man", "Captain America", "Superman"];

const [hero1, ...rest] = superheroes;
console.log(rest);

// ["Spiderman", "Iron man", "Captain America", "Superman"];

Summary

Object and array destructuring assignment provides an efficient method for extracting multiple properties or elements from an object or array, respectively, into new variables.

In this tutorial, we have seen how simple destructuring works in relation to both objects and arrays as well as how to work with nested data structures, set default parameters, and create a new object or array containing the non-destructured data.

It is not only useful in the examples presented, but also an important technique in object-oriented programming, where data is passed in and out of objects frequently.