我有这样的原始数据:
{
"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"
}
]
}
我想将数据转换如下:
{
"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
}
}
}
我尝试使用Underscore.js,但不是很成功,因为我是新手。
我到这里来:
_.groupBy(data, function(element) {
element.teamName + '#' + element.status
});
但我对如何继续无能为力。
答案 0 :(得分:1)
您可以先迭代对象的键和数组,然后获取包含的属性,然后计算相同的值。
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; }