I have a data json object structured like this:
data: [{
"aggregate": {
"path": "/home/page1",
"query": "name=todd"
},
"visits": 4,
"clicks": 7
},{
"aggregate": {
"path": "/home/page1",
"query": "name=matt"
},
"visits": 5,
"clicks": 17
},{
"aggregate": {
"path": "/home/page2",
"query": ""
},
"visits": 4,
"clicks": 7
},{
"aggregate": {
"path": "/home/page3",
"query": "term=dig"
},
"visits": 2,
"clicks": 20
},{
"aggregate": {
"path": "/home/page1",
"query": "term=dug"
},
"visits": 2,
"clicks": 11
}]
I am looking to end up with an aggregatedObject object like this:
[{
"path": "/home/page1",
"visits": 9,
"clicks": 24
},{
"path": "/home/page2",
"visits": 4,
"clicks": 7
},{
"path": "/home/page1",
"visits": 4,
"clicks": 31
}]
This is what I have so far:
let aggregatedObject = [];
_.each(data, function (item) {
if (!_.find(aggregatedObject, { path: item.aggregate.path })) {
aggregatedObject.push({
path: item.aggregate.path,
visits: item.visits,
clicks: item.clicks
});
//console.log('not found');
} else {
// so lost here
}
});
What I'm trying to do is if my new object doesn't have an item that matches the item I'm currently iterating through, I push it to the new object. So far I can successfully do this.
However, if I do find an item that matches the path in my new object (ignoring query), I have no idea how to update that item with the sum of the existing item's visits and clicks, and the one I'm iterating through.