javascript - 如何使用正则表达式对数组中的 Javascript 对象进行排序
问题描述
我正在调用 API 并获取包含大量对象的数组。数组中有数百个对象,其中一小段看起来像这样:
[
{
"name": "total_kills_glock",
"value": 70
},
{
"name": "total_kills_mac10",
"value": 39
},
{
"name": "total_kills_ump45",
"value": 136
},
{
"name": "total_shots_glock",
"value": 1262
},
{
"name": "total_hits_glock",
"value": 361
}
{
"name": "total_shots_mac10",
"value": 862
},
{
"name": "total_hits_mac10",
"value": 261
},
{
"name": "total_shots_ump45",
"value": 1610
},
{
"name": "total_hits_ump45",
"value": 598
}
]
有没有办法使用正则表达式对数组进行排序,看起来像这样:
[
{
"name": "glock",
"kills": 70,
"shots": 1262,
"hits": 361
},
{
"name": "mac10",
"kills": 39,
"shots": 862,
"hits": 261
},
{
"name": "ump45",
"kills": 136,
"shots": 1610,
"hits": 598
}
]
解决方案
您可以使用reduce()方法对数组项进行分组,使用split()方法从name
字符串中提取名称和操作。
var data = [{ "name": "total_kills_glock", "value": 70 }, { "name": "total_kills_mac10", "value": 39 }, { "name": "total_kills_ump45", "value": 136 }, { "name": "total_shots_glock", "value": 1262 }, { "name": "total_hits_glock", "value": 361 }, { "name": "total_shots_mac10", "value": 862 }, { "name": "total_hits_mac10", "value": 261 }, { "name": "total_shots_ump45", "value": 1610 }, { "name": "total_hits_ump45", "value": 598 } ];
var result = data.reduce((acc, curr) => {
let words = curr.name.split('_');
let name = words[2];
let action = words[1];
let item = acc.find(item => item.name === name);
if (item) {
item[action] = curr.value;
} else {
acc.push({
"name": name,
[action]: curr.value
});
}
return acc;
}, []);
console.log(result);
推荐阅读
- r - 连接不同维度的数据框并填补空白
- python - 数据框根据与另一个数据框的比较过滤行
- pandas - 猫图的 Seaborn FacetGrid
- ionic4 - 在 IOS 设备上测试 ionic 应用程序时出错
- java - 我无法运行我的黄瓜 jvm 报告
- unity3d - 长按和随机时间值
- authentication - 一个 ASP.NET Core 2.2 控制器中的多种身份验证方法
- reactjs - 错误:“在“@ckeditor/ckeditor5-build-classic”中找不到导出“默认”(导入为“ClassicEditor”)
- reactjs - componentDidMount 生命周期方法中子组件抛出的错误未在错误边界中捕获
- angular - 从ngx-chips(标签输入)中选择项目时Angular2 +打开模态