Assign items of arrays to multiple variable when creating it (Array Destructuring) Javascript(ES6)
Before ECMAScript 6 we got the array values using its index but using ES6 you can extract values from the array and assign them to variables when creating the array.
//First code example
const [value_1, value_2, value_3] = ["item_1", "item_2", "item_3"]
console.log(value_1);
console.log(value_2);
console.log(value_3);
//Second code example
const [fruits, vegetables] = [
[{"name": "Orange"}, {"name": "Grapes"}, {"name": "Banana"}],
[{ "name": "Potato" }, { "name": "Onion" }, { "name": "Lady fingers" }]
];
console.log(fruits);
console.log(vegetables);
In the code snippet, we have created an array that consists of three items and we want to extract these items and assign them to three variables while creating it.
In the second code example, we have an array that consists of two items. The first item has the different objects of fruits and the second item has different objects of vegetables. So when creating it we want to assign fruits array and vegetable array to the different variables. Before ES6 we used to do that by using array indexes as below
const fruits_vegetables = [
[{"name": "Orange"}, {"name": "Grapes"}, {"name": "Banana"}],
[{ "name": "Potato" }, { "name": "Onion" }, { "name": "Lady fingers" }]
];
const fruits = fruits_vegetables[0];
const vegetables = fruits_vegetables[0]
But using ES6 we can do that while creating our array as shown in the code snippet. It is also called Array Destructuring where we extract multiple array values.
Live Demo
const [score, subject, chapter] = [
90,
{"name": "Math", "code": "M01"},
"Arithmetic"
];
console.log(score);
console.log(subject);
console.log(chapter);
let [a, b, c, d] = ["a", "b", "c", "d"];
//the above code is equivalent to
const data = ["a", "b", "c", "d"];
a = data[0];
b = data[1];
c = data[2];
d = data[3];
const [data_1, data_2 = 'item_2'] = ['item_1'];
console.log(data_1);
console.log(data_2);
const [data_1, ,data_2] = ['value_1', 'value_2', 'value_3'];
console.log(data_1); // -> 'value_1'
console.log(data_2); // -> 'value_3'
- Javascript ES6 Destructuring
- Combine or merge two or multiple arrays into single array in Javascript
- Merge multiple arrays and strings into single array using Lodash
- JavaScript ES6 filtering object with multiple params
- Swapping two values using Destructuring in Javascript
- Lodash - Get common values from multiple arrays
- Javascript ES6 Array Filter