//json分组汇总
var json = [{
"name": "金辉",
"value": 100,
"year": 2020
}, {
"name": "金辉",
"value": 200,
"year": 2021
}, {
"name": "金辉",
"value": 150,
"year": 2022
}, {
"name": "金辉",
"value": 250,
"year": 2023
}, {
"name": "中骏",
"value": 100,
"year": 2020
}, {
"name": "中骏",
"value": 200,
"year": 2021
}, {
"name": "中骏",
"value": 150,
"year": 2022
}, {
"name": "中骏",
"value": 250,
"year": 2023
}];
var arr = eval('(' + json + ')');
var map = {},//记录分组名称
dest = [];//输出内容:分组名称+汇总值
for (var i = 0; i < arr.length; i++) {
var ai = arr[i];
if (!map[ai.name]) {//如果分组名称数组中不存在则在输出数组中新增
dest.push({
name: ai.name,
data: [ai.value]
});
map[ai.name] = ai;
} else {//如果在分组名称数组中存在则在输出数组中找到对应的分组名称汇总汇总值
for (var j = 0; j < dest.length; j++) {
var dj = dest[j];
if (dj.name == ai.name) {
dj.data.push(ai.value);
break;//找到即跳出
}
}
}
}
console.log(dest);
//分组汇总后数组
dest = [{
"name": "金辉",
"data": [100, 200, 150, 250]
}, {
"name": "中骏",
"data": [100, 200, 150, 250]
}]
json 分组
最新推荐文章于 2024-09-12 17:03:25 发布