gpt4 book ai didi

javascript - 使用 Javascript 或 Underscore 聚合数据

转载 作者:行者123 更新时间:2023-11-30 00:03:02 25 4
gpt4 key购买 nike

我有这样的原始数据:

{
"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
});

但我对如何进行一无所知。

最佳答案

您可以先迭代对象的键和数组并获取包含的属性,然后进行相同的计数。

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; }

关于javascript - 使用 Javascript 或 Underscore 聚合数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39595792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com