-2

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)

Niteesh Bhargava
  • 157
  • 1
  • 10
  • 1
    You cannot use destructuring assignment to both take an item off somewhere *and* clone it. Destructuring does not work that way - it's merely a shortcut to get properties off somewhere, e.g., `const { bar } = foo;` is the shorter version of `const bar = foo.bar`. You don't *also* manipulate the property on assignment. – VLAZ Mar 02 '22 at 10:44
  • 3
    It's not quite clear to me what the output value should be. If you want three objects in three different variables then what you have seems ok. – Felix Kling Mar 02 '22 at 10:44
  • 3
    pretty sure a function *is* a 'javascript shortcut solution' – pilchard Mar 02 '22 at 10:46

2 Answers2

0

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;
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48