How to reduce and sum a nested object array by key

I have an object array that goes like this:

data = {
    1: { // Day of week 
        10: [ // Hour of day
            {productName: 'a', total: 5},
            {productName: 'b', total: 1},
            {productName: 'c', total: 2},
            {productName: 'a', total: 4},
            {productName: 'b', total: 6}...
        ],
        12: [ // Hour of day
            {productName: 'a', total: 1},
            {productName: 'b', total: 2},
            {productName: 'a', total: 4}...
        ],
        14: [...]
    },
    2: {...} //Day of week - Goes up to 7
    ...
};

And I want to reduce the inner array by productName and sum the totals like so:

data = {
    1: { // Day of week 
        10: [ // Hour of day
            {productName: 'a', total: 9},
            {productName: 'b', total: 7},
            {productName: 'c', total: 2},
        ],
        12: [ // Hour of day
            {productName: 'a', total: 5},
            {productName: 'b', total: 2},
        ],
        14: [...]
        ...etc
    },
    2: {...} //Day of week
    ...
};

What's the best way about doing this?

I've been playing around with Array.reduce and .map and I can't seem to get it to work correctly, I'm having a hard time grasping it with the nested arrays in the data object.

I was going to go into a nested for loop but before doing so, is there someone who has a neat way of solving this?



Read more here: https://stackoverflow.com/questions/67375610/how-to-reduce-and-sum-a-nested-object-array-by-key

Content Attribution

This content was originally published by Readerino at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: