Home > Blockchain >  Cloning an Array without some fields
Cloning an Array without some fields

Time:02-24

I have an array like this, but i want to have copy of this array but without fields: name and price. Any ideas how to do it?

CodePudding user response:

Here is one possible implementation to achieve the objective.

Code Snippet

const origArr = [
  { id: 0, name: 'name1', amount: 10, price: 33.9 },
  { id: 1, name: 'name2', amount: 20, price: 24.9 }
];

const transformArray = arr => (
  arr.map(
    ({name, price, amount, ...rest}) => ({
      ...rest,
      quantity: amount
    })
  )
);

console.log(transformArray(origArr));

Explanation

  • Iterate through the origArr
  • De-structure the object to pick the name, price, amount props
  • Transform by excluding name, price & renaming amount to quantity
  • Related