Anjan Dutta

Extract Data from Arrays and Objects in JavaScript

Extract Data from Arrays and Objects in JavaScript

Updated on: 2024-01-16

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

The JavaScript destructuring assignment is a notable feature introduced in ES6. It simplifies the process of writing clear and concise JavaScript assignment expressions, allowing us to extract values from arrays or properties from objects.

How to extract data from array in javascript:

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

Let me describe the above code snippet step by step:

  1. var ten, twenty;: Declares two variables, ten and twenty, without initializing them.

  2. [ten, twenty] = [10, 20];: Utilizes destructuring assignment to assign values from an array to the variables ten and twenty. The values on the right side of the equal sign ([10, 20]) are an array with two elements, and the destructuring assignment syntax [ten, twenty] extracts and assigns these values to the corresponding variables.

Before extracting the values from an array, it's possible to both declare and assign a variable in a single line, as demonstrated below:

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

The above code snippet initializes two variables, ten and twenty, using destructuring assignment from an array [10, 20]. It then prints the value of both the variables to the console.

How to extract value from array in javascript

1var nameArr = ['Bob', 'Dan', 'George'];
2var [person1, person2, person3] = nameArr;
3console.log(person1);
4//Bob
5console.log(person2);
6//Dan
7console.log(person3);
8//George

Above code initializes an array `nameArr` with three string elements: 'Bob', 'Dan', and 'George'. Then, it uses destructuring assignment to assign these values to three variables: person1, person2, and person3. Finally, it prints the values to the console.

How to extract value from object in javascript:

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

Another way of getting data is shown below.

How to extract data from object in javascript

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.

Copy below code and Run here
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 using destructuring

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

Variable value Assignment using destructuring

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

Passing of Function parameter using destructuring

Copy below code and Run here
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 method.

How to get data from array of objects in javascript

The below example shows how to extract object from an array and then 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

how to extract array from object in javascript

1const country = {
2 name: 'Austria',
3 info: {
4 population: 8217280,
5 area: 32382,
6 language: ['Croatian', 'Slovenian', 'Hungarian', 'German']
7 }
8};
9
10({name, info: { population,area, language: l}} = country);
11
12console.log(population, l);

How to swap variable values using destructuring

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

Copy below code and Run Code
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});

Using Default values in destructuring

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.

Elision or ignoring returned values in destructuring

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.

Copy below code and Run here
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

How to extract remaining data from object using the javascript 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 {one: a, two: b, ...c} = {one: 1, two: 2, three: 3, four: 4};
6console.log(a); // 1
7console.log(b); // 2
8console.log(c); // { three: 3, four: 4 }

Destructuring prevents code redundancy and can be applied to any iterable on the right side of an assignment operator. While it is compatible with various iterators such as set, map, arrays, and objects, we will focus on array and object destructuring, which are the most commonly used patterns.

In conclusion, these examples highlight the flexibility and readability that destructuring provides in JavaScript. Whether dealing with arrays or objects, destructuring allows for concise and expressive code, enhancing the clarity and efficiency of variable assignments.