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