16

Is it possible to nest destructuring?

E.g. I want the first item in an array and in that array I want the first item of that child array.

Given:

let arr = [['foo'], ['bar']];

Is there an easier way to do:

let firstItem = arr[0][0];
chrisjlee
  • 21,691
  • 27
  • 82
  • 112

3 Answers3

22

Ah figured this out:

let [[firstItem]] = arr;

That would be the equivalent.

chrisjlee
  • 21,691
  • 27
  • 82
  • 112
12

Yes, it is possible to destructure nested arrays (and objects).

Let's consider this nested array [[1], [1, 2], [1, 2, 3]], which is a 2D array. To get the 1st child-array's 1st element,

let [[x]] = [[1], [1, 2], [1, 2, 3]]

To get the 2nd child-array's 1st element,

let [,[x]] = [[1], [1, 2], [1, 2, 3]]

Here, comma is used to skip elements. To get the 2nd element of the third child-array like this:

let [,,[,x]] = [[1], [1, 2], [1, 2, 3]]

If you want to retrieve a specific element as well as the remaining elements in an array, you can use the rest operator .... For example, to get the 3rd child-array's first element and the remaining elements separately,

let [,,[x, ...others]] = [[1], [1, 2], [1, 2, 3]] // x=1, others=[2, 3]
Ahmad Ferdous
  • 3,351
  • 16
  • 33
1

Here I am just assuming multiple items just to make syntax more clear.

let arr = [['foo','foo1'], ['bar','bar1']];
var a,b,c,d;
[[a,b],[c,d]] = arr;
console.log(a,b,c,d); // foo,foo1,bar,bar1
Santosh Kadam
  • 1,265
  • 14
  • 14