0

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.

HelpANoobOut
  • 213
  • 1
  • 5
  • 11

2 Answers2

1

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);
Barmar
  • 741,623
  • 53
  • 500
  • 612
-1

Idk man, Array.forEach is pretty effective, but you could create an Array.map() and predefine a function. E.G:

function func(car) {
car.total = car.price + car.tax;
}
let newData = data.map(func);

Also as a tip on the code logic, might want to use let or var instead of const because inflation, price changes, and tax increase/decrease are possible.

  • 1
    Note the requirement: "Don't want to mutate the original". This speaks to both your implementation and your `var/let/const` comment. – Scott Sauyet Jun 01 '22 at 14:14