Destructuring Arrays and Objects

Destructuring Arrays and Objects

Introduction

When you first hear about destructuring in JavaScript, it may appear hard, but it is actually one of the simplest concept in the language.

This article will explain what destructuring is and how to destructure arrays and objects quickly and easily.

Table of contents

  • Destructuring in JavaScript
  • How to Destructure an Array
  • How to Destructure an Object
  • Conclusion
  • References

Prerequisite

You should be familiar with Arrays, Objects, Template Literals and functions.

Destructuring In JavaScript

What does destructuring mean? According to Macmillan Dictionary, destructuring is "the process of unpacking a small part of something from the main part". This definition also applies to destructuring in JavaScript. As a result, destructuring allows us to extract values from arrays and properties from objects and store them in a variable. Let's look at some examples to help you understand.

How to Destructure an Array

Example 1:

First, consider how we might retrieve these elements without resorting to destructuring.

const array = [1,3,5];
const a = array[0];
const b = array[1];
const c = array[2];

console.log(a,b,c); // logs 1, 3, 5 to the console

Now let's use destructuring to retrieve the elements

const array = [1,3,5];
const [i,j,k] = array;

console.log(i,j,k); // logs 1, 3, 5 to the console

As we can see, destructuring helps us to unpack the values in the array and store them in a variable, unlike the first method where we have to go through the stress of specifying the index.

Example 2:

const artist = {
  name: 'Taylor  Swift',
  location: 'Nashville, Los Angeles, New York',
  albums: ['Red', 'Folklore', 'Speak Now', 'Reputation'],
  release: [2021, 2020, 2019, 2017],

  order: function(album1, release1) {
    return [this.albums[album1], this.release[release1]];
  }
};

Now we want to use destructuring method to retrieve the first and second album (element) from the albums array

const [first, second] = artist.albums; 
console.log(first, second) // logs Red Folklore to the console

What if we want to retrieve only the first and third elements and skip the second?

const [first, , second] = artist.albums; // Add a comma to the position you want to be skipped

console.log(first, second) //logs Red  Speak Now to the console

Here, adding a comma will skip 'folklore' the second element on the albums array

Example 3:

Another example is to have a function return an array, and we immediately destruct it; check the function in the artist object above.

console.log(artist.order(3, 1)); // logs this array ['Reputation', 2020] to the console

Now let's destruct this new array

const [album, year] = artist.order(3, 1);
console.log(album, year); // logs Reputation 2020 to the console

Nested Arrays

What happens if we have a nested array? How do we destruct it? Let's see how as shown in the example below

const nestedArr = [2, 3, [4, 5]];
const [x, , y] = nested; 

console.log(x, y); // logs 2, [4, 5] to the console

So, just like the previous example, we skipped the '3' by adding a comma in the array.

If we want to retrieve all elements from both the array and the nested array, then we simply have to do destructuring inside destructuring

const nestedArr = [2, 3, [4, 5]];

const [i, j, [k, l]] = nested; 
console.log(i, j, k, l); // logs 2 3 4 5 to the console

How to Destructure an Object

In JavaScript, we usually have functions with lots of parameters and so instead of defining the parameters manually, we can just pass an object into the function, and then the function will immediately destructure the object. Check the example below

Example 1: This function contains an object that was passed into the function as a parameter

orderAlbum: function({album1, release1, time, address})

But we can also set default values, now let's add values to the parameters in the function above

orderDelivery: function({album1 = 2, release1 = 0, time = '13:00', address}) {
    console.log(`Your order is being processed! ${this.albums[album1]} that was released in the year ${this.release[release1]} will be delivered to ${address} at ${time}.`);
}

The default values added to album1 and release1 represents their indexes respectively.

Note that orderAlbum property is part of the artist object

Next, is to call the object and pass in an object of an option (In this case, address)

artist.orderDelivery({
  address: '3B, Coker Street 120034, Lagos',
});

Now if we call the orderDelivery function, the console should show:

Your order is being processed! Speak now that was released in the year 2021 will be delivered to 3B, Coker Street 120034, Lagos at 13:00.

Example 2: Using the artist object, we want to destructure name, albums, and release.

Note: To destructure an object, you have to specify the name of the property

const artist = {
  name: 'Taylor  Swift',
  location: 'Nashville, Los Angeles, New York',
  albums: ['Red', 'Folklore', 'Speak Now', 'Reputation'],
  release: [2021, 2020, 2019, 2017],

  order: function(album1, release1) {
    return [this.albums[album1], this.release[release1]];
  }
};

const {name,   albums,   release} = artist;
console.log(name, albums,   release); // logs Taylor  Swift, ['Red', 'Folklore', 'Speak Now', 'Reputation'], [2021, 2020, 2019, 2017] to the console

We can use destructuring to change the name of the property

const {name: artistName, albums: records, release: yearOfRelease}

console.log(artistName, records, yearOfRelease); // logs same result but with new variable names

So artistName will replace name, records replace albums, and yearOfRelease replaces release.

Mutating variables while destructuring objects

let x = 5;
let y = 10;

const change = {x:15, y:20, z:25};
({x, y} = change); // wrap the destructuring assignment into parentheses

console.log(x, y); //this will switch the initial value of x, y to the new ones

Nested Objects

In this object, we will be creating two variables 'day' and 'hour' from the June object which will contain the value of 'day' and 'hour' the album will be released, don't forget that June is an object inside the releaseTime object which in turn is an object inside the artist object.

 const artist = {
  name: 'Taylor  Swift',
  location: 'Nashville, Los Angeles, New York',
  albums: ['Red', 'Folklore', 'Speak Now', 'Reputation'],
  release: [2021, 2020, 2019, 2017],

  releaseTime: {
    march: {
      day: 12,
      hour: 13,
    },
    august: {
      day: 23,
      hour: 10,
    },
    june: {
      day: 16,
      hour: 24,
    },
  }
};
const {june} = releaseTime;

console.log(june); //this will log day and hour with their values(numbers)

But we only want the values, so how do we go about it?

const {june: {
  day, hour} 
 } = openingHours;


 console.log(day, hour); // logs 16 and 24

Conclusion

The concept of destructuring, its definition, how it works, have all been thoroughly explained in this article.

We have learned what destructuring means in JavaScript, and also how to destructure arrays and objects

With this knowledge, you can conveniently extract multiple values from data stored in (possibly nested) objects and Arrays.

References