从 Javascript 中的多个索引解构项目的快捷方式

Shortcut for destructuring items from multiple indexes in Javascript

给定一个少于 160 项的数组,我想提取三个字段并复制它们;

 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

以下是我的有效方法

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

我想要的:寻找一种单行快捷方式解决方案,我可以在一个 javascript 语句中传递索引,在另一个数组中传递 return 字段(我知道我可以做一个函数,但只是想知道是否有 javascript 快捷方式解决方案)

您可以直接地址 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;

您可以获得物品,而不是副本,如下所示:

const itemsList = [{name:'Item-1'}, {name:'Item-2'}, {name:'Item-3'}];
const index_X = 0, index_Y = 1, index_Z= 2;

const { [index_X]: index_X_Item, [index_Y]: index_Y_Item, [index_Z]: index_Z_Item } 
  = itemsList;

console.log(index_X_Item, index_Y_Item, index_Z_Item);

要获取副本,您可以使用 Array#map:

const itemsList = [{name:'Item-1'}, {name:'Item-2'}, {name:'Item-3'}];
const index_X = 0, index_Y = 1, index_Z= 2;

const [index_X_Copy, index_Y_Copy, index_Z_Copy] = 
  [index_X, index_Y, index_Z].map(index => ({ ...itemsList[index] }));

console.log(index_X_Copy, index_Y_Copy, index_Z_Copy);