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];

3 Answers 3

22

Ah figured this out:

let [[firstItem]] = arr;

That would be the equivalent.

Sign up to request clarification or add additional context in comments.

1 Comment

you can destructure nested objects the same way fyi ^_^
13

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]

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.