Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning default value to variable in destructing nested array

I am wondering how to assign default values when destructing a nested array. I have myArr array which has a nested array [12, 25, 1, 6]


let  myArr = [11, 100,  33,  [12, 25, 1, 6], 77]

I want to assign a default value to four when destructing myArr as below


const[ one = 999, two = 999, three = 999, four = [ ], five = 999]  = myArr

And I also want to destructure elements of the nested array.

const[ one = 999, two = 999, three = 999, [innerOne = 1, ...rest ], five = 999]  = myArr

Is it possible to assign a default value to variable four and destructure the elements of the nested array [12, 25, 1, 6] concurrently in one line?

like image 641
nibble Avatar asked Jan 26 '23 11:01

nibble


1 Answers

You can do this by destructuring the array as an object. When destructuring an object, you can assign aliases, and destructure a property more than once (index 3 in this case).

const myArr = [11, 100,  33,  [12, 25, 1, 6], 77]

const { 
  0: one = 999, 
  1: two = 999, 
  2: three = 999, 
  3: four = [],
  3: [innerOne = 1, ...rest ],
  4: five = 999
} = myArr

console.log(one, two, three, four, innerOne, rest, five)
like image 141
Ori Drori Avatar answered Feb 01 '23 13:02

Ori Drori