How to destructure arrays and objects in JavaScript?

Before getting into destructuring, lets have a quick recap on arrays and objects.

  • Objects allows us to create a single entity that gather data items by key.

const emp = {

  name: “Anna”,

  id: “101”,

};

  • Array allows us to gather data items into an ordered list.

const emp = [“Anna”,”Tina”,”Tim”];

Destructuring introduced in ES6 allows us to unpack elements in an array or elements. It extracts multiple properties, items and values from an array or object into a separate variable.

Object Destructuring:

Syntax:
let { var1,var2} ={var1:val1, var2:val2}

To destruct object we use curly braces { }

Consider you have a student object with properties firstname and lastname.

let student = {

    firstname: "Anna",

    lastname: "Hills"

};
Prior to ES6:

For assigning properties and values to variables we have,

let student = {

    firstname: “Anna”,

    lastname: “Hills”

};

let firstName = student.firstname;

let lastName = student.lastname;

console.log(firstName);

console.log(lastName);

From ES6:
// assigning object attributes to variables
let student = {
    firstname: "Anna",
    lastname: "Hills"
};
// destructuring assignment
let { firstname, lastname} = student;
console.log(firstname); // Anna
console.log(lastname); // Hills
In the above example we have used the same variable names.
How to assign new variable name?
// assigning object attributes to variables
let student = {
    firstname: "Anna",
    lastname: "Hills"
};
// destructuring assignment to new variable
let { firstname:fname, lastname:lname} = student;
console.log(fname); // Anna
console.log(lname); // Hills

The order of the name in the object is not important we can also write as,

let {lastname, firstname} = student;
How to assign default values?

We can pass default values as follows,

let student = {
    firstname: "Anna",
    lastname: "Hills"
};
let { firstname, lastname, age = 22} = student;
console.log(age); //22
Output:

22

How to assign multiple object properties to single variable?
const student = {
    firstname: 'Anna',
    lastname: 'Hills',
    age: 25,
    gender: 'female'    
}
// destructuring assignment
// assigning remaining properties to rest
let { firstname, ...details } = student;

console.log(firstname); // Anna
console.log(details); // {lastname: 'Hills', age: 25, gender: 'female'}
Output:

Anna

{ lastname: ‘Hills’, age: 25, gender: ‘female’ }

Nested destructuring in objects:

In order to execute the nested destructuring assignment for objects, you have to enclose the variables in an object structure (by enclosing inside {}).

const student = {
    name: 'Anna',
    age: 26,
    details: {
        course: 'Javascript',
        fee: 2500
    }
}
// nested destructuring 
const {name, details: {course, fee}} = student;
console.log(name); // Anna
console.log(course); // Javascript
console.log(fee); // 2500
Output:

Anna

Javascript

2500

Array destructuring:

To destruct arrays we use square brackets [ ].

Syntax:
const [var1,var2,…] = arrayName;
Example:
const arrValue = ['Anna', 'Tina', 'Lena'];

// destructuring assignment in arrays
const [x, y, z] = arrValue;

console.log(x); 
console.log(y); 
console.log(z); 
Output:

Anna

Tina

Lena

How to assign default values?
let arr1 = [20];
// assigning default value 5 and 7
let [x = 10,  y = 9] = arr1;
console.log(x); // 20
console.log(y); // 9

In the above array we have one element so when we assign default values only y=9 is assigned and x=20 remains the same.

Output:

20

9

How to swap variables using destructuring assignment?
// program to swap variables
let x = 10;
let y = 20;
// swapping variables
[x, y] = [y, x];
console.log(x); // 20
console.log(y); // 10
Output:

20

10

How to skip assigning unwanted items in an array?

We can skip assigning unwanted items in an array to a local variable using comma ( , )

const arr1 = ['one', 'two', 'three'];
// destructuring assignment in arrays
const [x, , z] = arr1;
console.log(x); // one
console.log(z); // three
Output:

one

three

How to assign multiple elements to a single variable?

We can assign multiple elements to a single variable using spread syntax …

const arr1 = ['one', 'two', 'three', 'four'];
// destructuring assignment in arrays
// assigning remaining elements to y
const [x, ...y] = arr1;
console.log(x); // one
console.log(y); // ["two", "three", "four"]
Output:

one

[ ‘two’, ‘three’, ‘four’ ]

one is assigned to x variable. Rest of the elements are assigned to y variable.

Nested Destructuring Assignment in arrays:

In order to execute the nested destructuring assignment, you have to enclose the variables in an array structure (by enclosing inside []).

Nested destructuring in arrays is

// nested array elements
const arr1 = ['one', ['two', 'three', 'four']];
// nested destructuring assignment in arrays
const [a, [b, c, d]] = arr1;
console.log(a); // one
console.log(b); // two
console.log(c); // three
console.log(d); // four
Output:

one

two

three

four

Destructuring allows for instantly mapping an object or array to many variables.

Understanding rest and spread operator

ES6 has some great features that makes working with parameters and arrays easy. JavaScript uses three dots ( … ) for both the rest and spread operators. The main difference between these two operators is that rest operator collects a set of elements and stores them into a single array and spread operator expands an array of elements into a list of individual elements.

Spread operator:

Spread operator expands the values in an iterable like array or strings across zero or more arguments or elements. It is used to split up array of elements and object properties. Using spread operator we can combine two arrays more easily.

const arr1 = ['a','b','c'];
const arr2 = ['d','e','f'];
const combine = [ ...arr1, ...arr2];//spread operator
console.log(combine);
Output:

[ ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’ ]

When using spread, we are expanding a single variable into more.

Spread in function call:
function sum(n1,n2)
{
    console.log(n1+n2);
}
let arr=[10,20];
sum(...arr);//spread in function call
Output:

30

As you can see spread operator takes parameters and spreads them across arguments in function call.

What will happen if we have to work with unknown number of parameters?

Answer is using rest operator.

Rest operator:

It’s a collection of remaining elements. Useful for merging functional arguments into an array. We can use when we don’t know how many functional arguments are passed to our method.

const find_greater= (...args) => {

  console.log(args); /* lets see what's in args */

  return console.log(args.filter((x) => x > 25))

}

find_greater(25,36,42,12,17,9,58);
Output:

[25,36,42,12,17,9,58]

[36,42,58]

Another example,
function sum(first, ...others){

  for(let i=0; i<others.length; i++)

    first+=others[i];

  return first;

}

console.log(sum(12,14,22,15,9,7));

let [c,...rest] = [12,14,22,15,9,7];

console.log(...rest);

console.log(c);
Output:

79

14 22 15 9 7

12

Rest parameter have to be at the last because it collects all the remaining parameters into an array.

Rest is a collector. It collects the remaining elements.

Rest vs Spread Operator:
RestSpread
Rest operator allows us to pass an indefinite number of arguments to function by accumulating these several values into an array. Spread operator spreads or expands the values in an array or a string across one or more arguments.
The spread operator in JavaScript expands values in arrays and strings into individual elementsThe rest operator puts the values of user-specified data into a JavaScript array