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

Creating a new array with added value from 2 fields

Hello guys currently i have an array with some data:

 const data = [
      {car: 'Hyundai', price: '60.00', tax: '5.00', total: 0},
      {car: 'Honda', price: '80.00', tax: '7.00', total: 0},
      {car: 'Tesla', price: '100.00', tax: '10.00', total: 0},
  ]

Data set is bigger. Whats the best way to get a new array with the total(price + tax) calculated. Don’t want to mutate original. So i need this back:

const newData = [
      {car: 'Hyundai', price: '60.00', tax: '5.00', total: 65.00},
      {car: 'Honda', price: '80.00', tax: '7.00', total: 87.00},
      {car: 'Tesla', price: '100.00', tax: '10.00', total: 110.00},
  ]

I have a lot more fields so I was wondering if there was a more efficient and shorter code to do it then my current solution which is forEach then on the total key, i just do data.price + data.tax.

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 :

Use map() to create a new array from the old array. Use ellipsis to merge the new property into a copy of the old object.

const data = [
      {car: 'Hyundai', price: '60.00', tax: '5.00', total: 0},
      {car: 'Honda', price: '80.00', tax: '7.00', total: 0},
      {car: 'Tesla', price: '100.00', tax: '10.00', total: 0},
  ];
const newData = data.map((car) => ({...car, total: Number(car.price) + Number(car.tax)}));
console.log(newData);
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