Home > Enterprise >  Destructuring a JavaScript Array by a Variable Index
Destructuring a JavaScript Array by a Variable Index

Time:09-29

To my understanding, JavaScript arrays can be destructured according to a specific index by doing the following.

const { 3: selectedByIndex } = arr;

This would assign the value of the element at index 3 to the variable selectedByIndex.

Is there a way to pass in a variable index value to destructure the array? The below does not work, it seems to instead look for the index property on arr.

const index = 3;
const arr = [1, 2, 3, 4, 5]

const { index: selectedByIndex } = arr;

CodePudding user response:

Yes, you can by setting index inside the square brackets.

const index = 3;
const arr = [1, 2, 3, 4, 5]

const { [index]: selectedByIndex } = arr;

console.log(selectedByIndex)

CodePudding user response:

The same way you pass a variable key when creating an object -- put it in [].

const index = 3;
const arr = [1, 2, 3, 4, 5]

const { [index]: selectedByIndex } = arr;
console.log(selectedByIndex);

But unless this is just a part of a more complex destructuring pattern, arr[index] is obviously simpler.

CodePudding user response:

While this works

const a = [1, 2, 3];
const index = 2;

const [,,v1] = a;
// v1 = 3
const { [index]: v2 } = a;
// v2 = 3

The second solution (v2) is a bad design practice, because an array is not an object, but you are accessing it as one.

A better solution would be either

const v3 = a[index]; 
const v4 = a?.[index];

In other words, destructuring is when you know the format of the data structure. If not, JavaScript arrays don't care if you try to get an out-of-bound value, unless the value is not an array, in which case you need optional chaining (e.g. v4).

  • Related