
解析动态 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 将包含以下键值对:
- "事件等级": ["123", "789", "128"]
- "行政区域": ["456", "110", "654"]










