Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading