解析json字符串时,由于stattype的值是动态变化的,因此无法使用写死的if判断。我们可以采用更加灵活的方式来处理。
// 获取json字符串数组 var result = eval('(' + data + ')'); // 创建一个Map对象 var map = new Map(); // 遍历result数组 for (var i = 0; i < result.length; i++) { // 获取当前对象 var current = result[i]; // 获取statTotal数组 var statTotal = current.statTotal; // 遍历statTotal数组 for (var j = 0; j < statTotal.length; j++) { // 获取当前statTotal对象 var statTotalItem = statTotal[j]; // 获取statType和total var statType = statTotalItem.statType; var total = statTotalItem.total; // 如果map中没有statType,则添加 if (!map.has(statType)) { map.set(statType, []); } // 获取map中statType对应的数组 var array = map.get(statType); // 将total添加到数组中 array.push(total); } }
这样处理后,map中的键就是stattype,值就是对应stattype的所有total组成的数组。