Here is a JSON object that contains cost and author information. I am working on this in Express.js and using Underscore.
[
{
"Cost": 250,
"author": { "id": "2", "name": "Joe", "workId": "5" }
},
{
"Cost": 450,
"author": { "id": "2", "name": "Joe", "workId": "6" }
},
{
"Cost": 150,
"author": { "id": "3", "name": "Tam", "workId": "7" }
},
{
"Cost": 250,
"author": { "id": "2", "name": "Joe", "workId": "8" }
},
{
"Cost": 350,
"author": { "id": "3", "name": "Tam", "workId": "9" }
}
]
The desired output is:
Joe 950
Tam 500
I attempted to achieve this with the following code:
var iw={};
iw = Object.keys(myJsonObject.reduce((iw, curr) => {
iw[curr.author.id].cost += parseInt(curr.cost);
return iw;
}, iw)).map(key => iw[key]);
console.log("New ::"+iw);
However, I encountered an error:
TypeError: Cannot read property 'cost' of undefined
at Object.keys.myJsonObject.reduce (repl:3:7)
at Array.reduce (<anonymous>)
New ::[object Object]