JavaScript: ES6 Destructuring assignment, extract data from arrays and objects

The ES6 destructuring assignment is another feature deployed as a part of the ECMAScript release in 2015. Destructuring is a simple javascript expression, that is used to unpack values from an array, or unpack properties from an object.

Basically, it works with any iterable on the right side of an assignment operator. Even though destructuring works with all kind of iterators like set, map, array and objects, here we will describe array and object destructuring as these are the most commonly used patterns.

Basic syntax (Array patterns):

var ten, twenty;
[ten, twenty] = [10, 20];
console.log(ten); //10
console.log(twenty); //20

We can also declare and assign in the same line like below:

var [ten, twenty] =[10, 20];
console.log(ten); //10
console.log(twenty); //20

Basic syntax (Object patterns):

var ten, twenty;
({ten, twenty} = {x:10, y:20});
console.log(ten); //10
console.log(twenty); //20

We can achieve the same result by doing:

var numbers = {x: 10, y: 20};
var {ten, twnty} = numbers;
console.log(ten); //10
console.log(twenty); //20

Destructuring vs constructing data in javascript:

Javascript has the ability to construct multiple data at a time. For example,

const response = {status: 200, message: "OK"};

Here, multiple data getting assigned in a single declaration.
Similarly, there was no direct feature in javascript for deconstructing or extracting multiple data at a time until ES6 introduced destructuring.

const response = {status: 200, message: "OK"};
const { status: s, message: m } = response ;
// s = 200
// m = "OK"

Where can we use ES6 Destructuring?

A smart implementation of destructuring can resolve a wide range of problems. Problems varying from variable declarations to swapping values or even iterating through complex objects in a loop, all can be handled using ES6 destructuring.

Variable declarations:

const [ten] = [10, 20, 30, 40]; //ten = 10
let [ten] = [10, 20, 30, 40]; //ten = 10
var [ten] = [10, 20, 30, 40]; //ten = 10

Assignments:

[rose] = ['red', 'green', 'blue']; //rose= 'red'

Function parameter:

function sumOfFirstTwo([x, y]=[0, 0]) {
	return x+y;
}
sumOfFirstTwo([7, 3, 9, 14]); //10
sumOfFirstTwo(); //0

Here, in the first function call, x and y will get values 7 and 3 respectively. But, in the second function call it will return zero because, if you look closely, we have passed default parameters [0, 0] in the function declaration. This is a good way of handling an exception.

Destructuring of a for-of iteration:

We can also use destructuring with for-of loops like below example. This approach helps us in getting the current array index as well as distinct value for the same index:

let numbers = [ 'zero', 'ten', 'hundred', 'thousand'];
for (const [index, element] of numbers.entries()) {
    console.log(index, element);
}
// Output:
// 0 zero
// 1 ten
// 2 hundred
// 3 thousand

And here is another interesting example. This example shows how to iterate through a complex objects’ value without using an index:

const countries = [
{
	name: 'Austria',
	info: {
	population: 8217280,
	area: 32382
	}
},
{
    name: 'Belgium',
    info: {
    population: 10431477,
    area: 11787
    }
}]

for (var {name: n, info: {population: p}} of countries) {
  console.log('Name: ' + n + ', Population: ' + p);
}
//Austria, 8217280
//Belgium, 10431477

Variable value swapping:

Using destructuring, swapping of variable value is really easy. Below example exactly shows how it is done.

let ten = 20;
var twenty = 10;

[ten , twenty ] = [twenty , ten ];
console.log(ten ); // 10
console.log(twenty ); // 20

ES6 Destructuring patterns:

Destructuring involves a source and a target. The source is always the data to be destructured or right-hand side of an assignment. Whereas target is a pattern that is to be used on the left-hand side of an assignment.
A target can be any of the three following patterns:

Variable:

var num = 20;

This is a simple variable assignment.

Array pattern:

[<pattren>, <pattern>]

const [a, b] = [10, 20];

Object pattern:

{<pattren>, <pattern>}

const ({a,b} = {10,20});
{first: , secod: }
const ({a:x, b:y} = {10, 20});

Default values:

Default values can be assigned to destructuring target variables. The advantage of it is, if an extracted assignment has an undefined value then the default value will be assigned to the target. This is a good practice of handling exception. The syntax is as follows:

let x, y;
[x=0, y=0] = [1];
console.log(x); // 1
console.log(y); // 0

Here a default value 0 will be assigned in case if no corresponding value extracted from the destructuring assignment (in our case [1]).

Elision or ignoring returned values:

In some cases, there might be a requirement of ignoring certain value(s) during destructuring of an assignment. It can be done using the following syntax:

const [,, two, three] = [0, 1, 2, 3]; 
// two = 2
// three = 3
const [a,, b, c] = [0, 1, 2, 3]; 
//a = 0
//b = 2
//c = 3

Rest operator (…) :

Rest operator lets us assign the rest of an iterable to a target variable.

let [x, ...y] = [4, 12, 20];
console.log(x); // 4
console.log(y); // [12, 20]
let {x, y, ...rest} = {one: 1, two: 2, three: 3, four: 4}
//x = 10 
//y = 20 
// rest = { three: 3, four: 4 }

The spread operator (…) looks same but does the opposite of rest operator and used to spread values in an array.

Proudly powered by WordPress | Theme: Baskerville.

Up ↑

Bitnami