Javascript programming articles and tutorials for beginner | Anjan Dutta

Extract Data from Arrays and Objects in JavaScript

Extract Data from Arrays and Objects in JavaScript

In this blog, we are going to explore how to extract data from arrays and objects in javaScript using destructuring.

JavaScript 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.

Syntax (Array patterns):

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

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

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

Syntax of javascript destructuring(Object patterns):

1var ten, twenty;
2({ten, twenty} = {ten:10, twenty:20});
3console.log(ten); //10
4console.log(twenty); //20

We can achieve the same result by doing:

1var numbers = {ten: 10, twenty: 20};
2var {ten, twenty} = numbers;
3console.log(ten); //10
4console.log(twenty); //20

Javascript destructuring vs constructing data:

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.

1const response = {status: 200, message: "OK"};
2const { status: s, message: m } = response ;
3// s = 200
4// 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

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

Assignments

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

Function parameter

1function sumOfFirstTwo([x, y]=[0, 0]) {
2 return x+y;
3}
4
5sumOfFirstTwo([7, 3, 9, 14]); //10
6sumOfFirstTwo(); //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.

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

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

1const countries = [
2{
3 name: 'Austria',
4 info: {
5 population: 8217280,
6 area: 32382
7 }
8},
9{
10 name: 'Belgium',
11 info: {
12 population: 10431477,
13 area: 11787
14 }
15}]
16
17for (var {name: n, info: {population: p}} of countries) {
18 console.log('Name: ' + n + ', Population: ' + p);
19}
20//Austria, 8217280
21//Belgium, 10431477

Variable value swapping

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

1let ten = 20;
2var twenty = 10;
3[ten , twenty ] = [twenty , ten ];
4console.log(ten ); // 10
5console.log(twenty ); // 20

Extract data from arrays and objects in javascript

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.

1/* Variable */
2// This is a simple variable assignment.
3var num = 20;
4
5/* Array pattern */
6
7// [<pattren>, <pattern>]
8
9const [a, b] = [10, 20];
10
11/* Object pattern */
12
13// {<pattren>, <pattern>}
14
15const ({a,b} = {10,20});
16const ({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.

1let x, y;
2[x=0, y=0] = [1];
3console.log(x); // 1
4console.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.

1const [,, two, three] = [0, 1, 2, 3];
2// two = 2
3// three = 3
4
5const [a,, b, c] = [0, 1, 2, 3];
6//a = 0
7//b = 2
8//c = 3

Rest operator (...)

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

1let [x, ...y] = [4, 12, 20];
2console.log(x); // 4
3console.log(y); // [12, 20]
4
5let {x, y, ...rest} = {one: 1, two: 2, three: 3, four: 4}
6//x = 10
7//y = 20
8// 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.

Edit this page on GitHub