javascript - 如何聚合 JSON 以显示每个相同值的计数
问题描述
我从我的服务器响应中获得了以下数据:
var data = [
{
project: {
name: "KB",
$type: "Project"
}
},
{
project: {
name: "Test",
$type: "Project"
}
},
{
project: {
name: "Test",
$type: "Project"
}
},
{
project: {
name: "KB",
$type: "Project"
}
},
{
project: {
name: "Test",
$type: "Project"
}
},
{
project: {
name: "Test",
$type: "Project"
}
}
];
我需要为以下步骤准备数据。理想情况下,我需要得到以下输出:
var aggregatedData = [
{
projectName: "KB",
count: 2
},{
projectName: "Test",
count: 4
},
];
可能吗?如果是这样,使用 jQuery 实现这一点的最佳方法是什么?
解决方案
你可以这样做 -
var data = [{
project: {
name: "KB",
$type: "Project"
}
},
{
project: {
name: "Test",
$type: "Project"
}
},
{
project: {
name: "Test",
$type: "Project"
}
},
{
project: {
name: "KB",
$type: "Project"
}
},
{
project: {
name: "Test",
$type: "Project"
}
},
{
project: {
name: "Test",
$type: "Project"
}
}
];
var hashMap = {}
data.map(element => {
// if the key(name) is inserted in our hashmap, just increment the count
// if the key isn't present, then just assign the count of that key(name) as 1 and increment next time onwards
hashMap[element.project.name] = hashMap[element.project.name] + 1 || 1;
});
// our count for each name is ready...just getting the result ready in our desired format
var aggregatedData =
Object.keys(hashMap).map(element =>
({
projectName: element,
count: hashMap[element]
})
)
// And done ... :)
console.log(aggregatedData);
我们在上述方法中所做的是创建一个变量,该变量将充当 out hashmap。它将遍历data
数组,并且对于数组中的每个元素data
,我们正在计算每个唯一名称的出现次数。
最后,我们正在迭代创建的 hashmap 并使用存储在 hashmap 中的键值对(它们只是出现次数对的名称),并使用它以我们所需的格式获取聚合数据。
推荐阅读
- javascript - 你知道为什么每次我输入输入时都会执行 useEffect 吗?
- google-cloud-platform - 虚拟机服务器升级会影响我的项目吗
- html - 如何修复有调整大小问题的滑块?
- javascript - “不能返回未定义的长度”的具体情况
- javascript - 如何让视差图像放大超出父 div 的范围?
- python - 根据条件将行合并在一起
- amazon-cognito - 试图了解一些 AWS Cognito 功能
- ios - 从钥匙串读取时如何跳过身份验证 UI
- sql - 连接到 SQL Server 的异常 - 执行超时已过期(立即显示)
- php - 无法使用 PHP cURL 连接到 xapi