Reputation: 2245
I have a raw data like this:
{
"Team1": [
{
"priority": "P0",
"status": "Open",
"teamName": "Team1"
},
{
"priority": "P1",
"status": "Closed",
"teamName": "Team1"
},
{
"priority": "P0",
"status": "Closed",
"teamName": "Team1"
}
],
"Team2": [
{
"priority": "P1",
"status": "Open",
"teamName": "Team2"
}
]
}
I would like to transform the data as follows:
{
"Team1": {
"teamName": "Team1",
"Open": {
"P0": 1,
"P1": 0
},
"Closed": {
"P0": 1,
"P1": 1
}
},
"Team2": {
"teamName": "Team2",
"Open": {
"P0": 0,
"P1": 1
},
"Closed": {
"P0": 0,
"P1": 1
}
}
}
I'm trying with Underscore.js, but not very successful since I'm novice in this.
I am till here:
_.groupBy(data, function(element) {
element.teamName + '#' + element.status
});
But I'm clueless on how to proceed.
Upvotes: 2
Views: 2042
Reputation: 386680
You could first iterate the object's keys and the arrays and get the included properties and then the same for the count.
var data = { "Team1": [{ "priority": "P0", "status": "Open" }, { "priority": "P1", "status": "Closed" }, { "priority": "P0", "status": "Closed" }], "Team2": [{ "priority": "P1", "status": "Open" }] },
keys = Object.keys(data),
priorities = new Set(),
grouped = {};
keys.map(k => data[k].forEach(a => priorities.add(a.priority)));
keys.map(k => {
grouped[k] = grouped[k] || {};
data[k].forEach(a => {
grouped[k][a.status] = grouped[k][a.status] || [...priorities].reduce((r, b) => (r[b] = 0, r), {});
grouped[k][a.status][a.priority]++;
});
});
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1