1

How can I replace accessing the temp variable values from the following code extract? I have tried to get all values through the default JS code, however, I would like to use destructuring here

const temp = context.options[0]; // <----- here
const avoidPattern = [
    'foo', 'bar', 'abc', 'value', 'temp', 'num'
];


return [...avoidPattern, ...temp]
Aleksandrs
  • 33
  • 6
  • If you mean using destructuring to access the first element of a list: `const [temp, ...rest] = context.options;` – Anson Miu Apr 10 '21 at 09:59

5 Answers5

5

This can also be possible if we destructure object and array at the same time.

const context = { options: [1, 2, 3] };
const { options: [temp] } = context;

console.log(temp);
DecPK
  • 24,537
  • 6
  • 26
  • 42
1

You might use this

const context = { options: [1,2,3] }
const [temp] = context.options;

console.log(temp)
hgb123
  • 13,869
  • 3
  • 20
  • 38
1

If you want to destructure the first element out of the options array.

  1. You can first destructure the options property from the context object.
  2. Then you can destructure the first item from the options array.

const context = { options: [1, 2, 3] };

// Destucture the options key property
const {options} = context
console.log(options) // [1,2,3]

// Next, destructure the first item from the array
const [first] = options
console.log(first) // 1

You can also combine the two steps mentioned above using the colon : operator, which is used to provide an alias while destructing an object.

const context = { options: [1, 2, 3] };

// Destucture the options property 
// and in the alias destructure the first item of the array
const {options: [first]} = context
console.log(first) // 1
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
0

let arr=['data','title','image']; 

let [first]=arr[1];

console.log(first);
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • `arr[1]` will be `title` and when you destructure it will give you the first character from it `t` – DecPK Apr 10 '21 at 13:32
  • yes! as in question he requiresshow data on index so i write my code arr[1] as first instead of first you can write second let arr=['data','title','image']; let [second]=arr[1]; console.log(second); – Siddhesh Shinde Apr 12 '21 at 06:35
0

An interesting that Array in JavaScript is an object, So you can destructure an array as object like this

const context = { options: [1, 2, 3] };
const { options } = context; // [1, 2, 3]
const {0:firstItem } = options;
console.log(firstItem);
As you can see, key of options array is integer number. Actually, it's index. In this way, you can destructure an array with the long array by index in the that way.

More details here: Object destructuring solution for long arrays?

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56