如何解析动态变化 json 字符串中的 stattype?
问题背景:
后台返回了一个 json 字符串,需要在前端通过 js 进行解析,将其中的 stattype 提取出来,并根据其动态变化的情况,将相应的数据值存入 map 集合中。
分析:
要解决这个问题,关键在于动态处理 stattype 的变化。我们可以使用以下步骤:
1. 初始化一个 map 集合
var map = new map();
2. 遍历 json 字符串中的 stattotal 字段
for (var i = 0; i < result.length; i++) { for (var j = 0; j < (result[i].stattotal).length; j++) { // 处理 stattype } }
3. 动态处理 stattype
可以使用以下代码来动态处理 stattype:
var stattype = result[i].stattotal[j].stattype; if (!map.has(stattype)) { map.set(stattype, []); }
4. 存入相应的数据值
根据 stattype,将相应的数据值存入 map 的键值对中:
map.get(stattype).push(result[i].stattotal[j].total);
示例代码:
var legend = [];//图例 var result = eval('(' + data + ')');//json字符串 var map = new Map(); for (var i = 0; i < result.length; i++) { for (var j = 0; j < (result[i].statTotal).length; j++) { var statType = result[i].statTotal[j].statType; if (!map.has(statType)) { map.set(statType, []); } map.get(statType).push(result[i].statTotal[j].total); } }
使用此代码,可以动态地提取 stattype 并将其与相应的数据值一起存入 map 集合中。
以上就是如何从动态变化的 JSON 字符串中解析并存储 statType 数据?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号