
解析动态 json 字符串为键值对映射
给定一个 json 字符串,我们需要将其解析为一个 javascript 对象,并以键值对映射的形式存储字段值。
问题重述
如何将以下 json 字符串解析为一个可变 stattype 映射?
[
{
"name": "2015年",
"stattotal": [
{
"total": "123",
"stattype": "事件等级"
},
{
"total": "456",
"stattype": "行政区域"
}
]
},
{
"name": "2016年",
"stattotal": [
{
"total": "789",
"stattype": "事件等级"
},
{
"total": "110",
"stattype": "行政区域"
}
]
},
{
"name": "2017年",
"stattotal": [
{
"total": "128",
"stattype": "事件等级"
},
{
"total": "654",
"stattype": "行政区域"
}
]
}
]解答
const data = JSON.parse(jsonString);
const map = new Map();
// 按年份迭代
for (let year of data) {
// 按统计类型迭代
for (let stat of year.statTotal) {
// 如果映射中不存在该统计类型
if (!map.has(stat.statType)) {
// 创建一个类型数组并添加到映射中
map.set(stat.statType, []);
}
// 将年的总数添加到该类型数组中
map.get(stat.statType).push(stat.total);
}
}结果
执行上面的代码后,map 将包含以下键值对:
以上就是如何将动态 JSON 字符串解析为键值对映射,以存储不同统计类型下的数据?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号