I have some customer data in an array of javascript objects that looks as such:
const clientData = [ { client: 'Pizza Hutt', food_cost: 400.00, prev_year_food_cost: 450.00, }, { client: 'Pizza World', food_cost: 500.00, prev_year_food_cost: 650.00, }, ];
I would like to loop over and get the difference between food_cost
and prev_year_food_cost
for each client. So ideally, I would have a new object containing client
, food_cost
and the difference.
[ { client: 'Pizza Hutt', food_cost: 400.00, difference: 50.00, }, { client: 'Pizza World', food_cost: 500.00, difference: 150.00, }, ];
I have tried this but its not quite right. It’s pseudo code.
const comparisonData = []; for (let i = 0; i < data.length; i += 1) { const item = { ...data[i] }; // console.log(item); Object.keys(item).forEach((key) => { if (key !== 'campaignname' && !key.includes(comparisonPeriodData.excluded_period)) { Do calculations here } } }); push data onto comparisonData }
Advertisement
Answer
You can use Array#map
to apply the transformation over each object, using Math.abs
to find the absolute difference.
We can use destructuring to remove the prev_year_food_cost
from the object.
This can be made more configurable by using the bracket syntax:
let clientData = [{ client: 'Pizza Hutt', food_cost: 400.00, prev_year_food_cost: 450.00, }, { client: 'Pizza World', food_cost: 500.00, prev_year_food_cost: 650.00, }]; const difference = (arr, key) => { return arr.map(o => { const { ["prev_year_" + key]: prev, ...rest} = o; return { ...rest, difference: Math.abs(o["prev_year_" + key] - o[key]) } }); } console.log(difference(clientData, "food_cost")); clientData = [{ client: 'Pizza Hutt', water_cost: 400.00, prev_year_water_cost: 450.00, }, { client: 'Pizza World', water_cost: 500.00, prev_year_water_cost: 650.00, }]; console.log(difference(clientData, "water_cost"));