I have some customer data in an array of javascript objects that looks as such:
JavaScript
x
13
13
1
const clientData = [
2
{
3
client: 'Pizza Hutt',
4
food_cost: 400.00,
5
prev_year_food_cost: 450.00,
6
},
7
{
8
client: 'Pizza World',
9
food_cost: 500.00,
10
prev_year_food_cost: 650.00,
11
},
12
];
13
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.
JavaScript
1
13
13
1
[
2
{
3
client: 'Pizza Hutt',
4
food_cost: 400.00,
5
difference: 50.00,
6
},
7
{
8
client: 'Pizza World',
9
food_cost: 500.00,
10
difference: 150.00,
11
},
12
];
13
I have tried this but its not quite right. It’s pseudo code.
JavaScript
1
13
13
1
const comparisonData = [];
2
for (let i = 0; i < data.length; i += 1) {
3
const item = { data[i] };
4
// console.log(item);
5
Object.keys(item).forEach((key) => {
6
if (key !== 'campaignname' && !key.includes(comparisonPeriodData.excluded_period)) {
7
Do calculations here
8
}
9
}
10
});
11
push data onto comparisonData
12
}
13
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:
JavaScript
1
15
15
1
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, }];
2
3
const difference = (arr, key) => {
4
return arr.map(o => {
5
const { ["prev_year_" + key]: prev, rest} = o;
6
return { rest,
7
difference: Math.abs(o["prev_year_" + key] - o[key])
8
}
9
});
10
}
11
console.log(difference(clientData, "food_cost"));
12
13
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, }];
14
15
console.log(difference(clientData, "water_cost"));