I need some advice on the proper way to attain my goal of applying group by and sum on JSON data.
Some server-side code actually generates a JSON that I have to work with :
[
{
"siteDetails": {
"printerCode": "660103684",
"siteId": "UTT212303-STB-2040-0003"
},
"printingMaterialCode": "400000033",
"printingQuantity": 400,
"approved": true
},
{
"siteDetails": {
"printerCode": "660103684",
"siteId": "UTT212303-STB-2040-0002"
},
"printingMaterialCode": "400000033",
"printingQuantity": 600,
"campaignId": "DATAS00002",
},
{
"siteDetails": {
"printerCode": "660103684",
"siteId": "UTT212303-STB-2040-0001"
},
"printingMaterialCode": "400000034",
"printingQuantity": 300,
"campaignId": "DATAS00002",
}
]
Now, I need to apply some operation (maybe groupby and sum) to get the below result :
[
{
"printingMaterialCode": "400000033",
"printingQuantity": 1000
"approvedQuantity": 400
},
{
"printingMaterialCode": "400000034",
"printingQuantity": 300,
}
]
Basically, the output is printingQuantity and approvedQuantity SUM per printingMaterialCode.
3
Answers
You can make use of
Map
as:We can build this on
reduce
in a fairly straightforward manner, with something like this:But I think it’s cleaner to use some generic helper functions to handle the grouping and summing, and make your code a little more specific to your requirements, with something like this:
Here,
group
takes a key-extraction function and returns a function which takes an array of values and return an array of arrays of the elements which map to the same key. So for instance, to group an array of numbers by their last digits, we could do this:If you’re using a library that has a
groupBy
function, then you could replace this with something likesum
, of course, just totals an array of numbers.So
combine
then groups the numbers into likeprintingMaterialCode
values, thenmap
s the result into an object with your requested properties.This has one difference from your requested structure, and that is that the group that has no
approved
entries, still has anapprovedQuantity
field; it’s just set to zero. I personally prefer this behavior, as consistent data is always a win. But if you wanted to change that, you could replace this line:with this:
However, that introduces some ugliness to our function.