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

Cloning an Array without some fields

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?

>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

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