Search code examples
javascriptarraystypescriptdestructuring

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

  • You can get the items, not copies, like this:

    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);

    To get copies, you can use 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);