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.

2
  • 2
    Using a .map() but i think this will be slower (if efficiency is your priority use a for) Commented May 31, 2022 at 22:05
  • Thank you guys for the links. I guess i wasn't looking for the right question. Commented May 31, 2022 at 22:13

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Note the requirement: "Don't want to mutate the original". This speaks to both your implementation and your var/let/const comment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.