How to sum JSON object key, value using javascript

How to sum JSON object key, value using javascript
0

#1

Hi all, I have the following JSON data Structure { "Shiva": [ { "allocations":{ "week1":1, "week2":1, "week3":1 }, "humanResourceId":"1" }, { "resourceName":"Shiva", "allocations":{ "week1":0.5, "week2":0.5, "week3":0.5 }, "humanResourceId":"1" } ], "Deepesh": [ { "allocations":{ "week1":0.74, "week2":1, "week3":0.74 }, "humanResourceId":"2" }, { "allocations":{ "week1":1, "week2":1, "week3":1 }, "humanResourceId":"2" } ] }

How to sum the allocation key of above JSON object to get this new JSON object:

{ "Shiva": [ { "allocations": { "week1":1.5, "week2":1.5, "week3":1.5 }, "humanResourceId":"1" } ], "Dipesh": [ { "allocations": { "week1":1.74, "week2":2, "week3":1.74 }, "humanResourceId":"2" } ] }

I am new to JavaScript and any help will be appreciated: Thank You in advance


#2

there are lots of good Javascript lessons on FreeCodeCamp , will you consider going through them? Your question is not a hard one and with some practice you can easily write this program that you need.

If you don’t have time though, please share the code you wrote so far and the test cases it has passed/failed so far so we can give you targeted help.


#3

Hi, I have done this, I am confused to implement map reduce here: anyhelp or suggestions

data_dict={

 }
Object.keys(data).forEach(element => {

    new_dict={}
     data[element].forEach(elements => {
        // console.log(elements.allocations.week1)
        
        Object.keys(elements.allocations).forEach(keys => {
            if(!new_dict.hasOwnProperty(keys)){
                new_dict[keys] = Number(elements.allocations[keys])
                
            }
            else if(new_dict.hasOwnProperty(keys)){
                new_dict[keys] += Number( elements.allocations[keys])
            }

            
               })
    
        
    });
    data_dict[element]=new_dict
});
console.log(data_dict)

#4

But your solution does not have the “humanResourceId” in each object as you specified in your original post.