I am trying to merge JS objects together that have the same key. In this case the key I plan to use is the "time" field, and then for each time I want to include every "app" as a key, and "sum" as its value. The other fields I do not plan to include.
I've tried a few routes but still having trouble, code below:
var data = [
{
"eventdate": 1561334400000,
"app": "cloudmark-desktop",
"sum": 2970,
"events": "2.9KiB",
"time": "00:06"
},
{
"eventdate": 1561334400000,
"app": "dns",
"sum": 519169,
"events": "507.0KiB",
"time": "00:06"
},
{
"eventdate": 1561334400000,
"app": "cloudmark-desktop",
"sum": 999,
"events": "507.0KiB",
"time": "01:06"
},
{
"eventdate": 1561334400000,
"app": "dns",
"sum": 999,
"events": "507.0KiB",
"time": "01:06"
}
];
const result = data.reduce(function (r, e) {
return Object.keys(e).forEach(function (k) {
if (!r[k]) r[k] = [].concat(e[k])
else r[k] = r[k].concat(e[k])
}), r
}, {})
console.log(result)
This is how I want the data to output:
[
{
"time": "00:06",
"cloudmark-desktop": 2970,
"dns": 519169
},
{
"time": "01:06",
"cloudmark-desktop": 999,
"dns": 999
}
]
Any help appreciated! Thanks