'Shortcut for destructuring items from multiple indexes in Javascript
Given an array of less than 160 items, I want to extract three fields and make a copy of them;
const item1 = {name:'Item-1'};
const item2 = {name:'Item-1'};
const item1 = {name:'Item-1'};
...........
const item_N_minus_one = {name:'Item-N_minus_one'};
const item_N = {name:'Item-N'};
const itemsList = [{item1}, {item2} ..... upto {itemN}]
// Where n <= 160
Below is my approach which is working
const index_X = 23, index_Y = 45, index_Z= 56; // Can not exceed beyond 160 in my case
const item_XCopy = {...itemsList[index_X]};
const item_YCopy = {...itemsList[index_Y]};
const item_ZCopy = {...itemsList[index_Z]};
What I want : Looking for a one liner shortcut solution where I can pass indexes in one javascript statement and return fields in another array(I know I can make a function, but just wondering if there is a javascript shortcut solution)
Solution 1:[1]
You could address directly and assign to new variable names.
const
index_X = 23,
index_Y = 45,
index_Z = 56,
{
[index_X]: { ...item_XCopy },
[index_Y]: { ...item_YCopy },
[index_Z]: { ...item_ZCopy }
} = itemsList;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
