关于一个动态 json 字符串的解析问题
问题
我们从后台获取到一个包含动态键名的 json 字符串,需要将其解析成一个 javascript 类型,该类型包含一个键值对,其中键是动态键名,值是键名对应的值。
问题示例
给定以下 json 字符串:
[ { "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": "行政区域" } ] } ]
目标是将其解析成一个类型为:
{ "事件等级": ["123", "789", "128"], "行政区域": ["456", "110", "654"] }
解决方案
function parsedynamicjson(data) { const result = json.parse(data); const map = new map(); // 遍历 json 对象 for (const item of result) { // 遍历 stattotal 数组 for (const stat of item.stattotal) { // 获取 stattype 并添加到 map 中 const stattype = stat.stattype; if (!map.has(stattype)) { map.set(stattype, []); } // 将 total 添加到 map 中 const totalarray = map.get(stattype); totalarray.push(stat.total); } } // 返回 map 作为 javascript 对象 return object.fromentries(map.entries()); }
使用方法
const jsonString = '[...JSON string from example...]'; const resultObject = parseDynamicJson(jsonString); console.log(resultObject); // 输出:{ "事件等级": ["123", "789", "128"], "行政区域": ["456", "110", "654"] }
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号