参考链接为:https://www.jianshu.com/p/c50515d369c4
实际项目demo如下:
var oldData = [
{
"classid": 219,
"classname": "(01)班",
"gradeid": 7,
"gradename": "初中一年级",
},
{
"classid": 224,
"classname": "(02)班",
"gradeid": 7,
"gradename": "初中一年级",
},
{
"classid": 228,
"classname": "(08)班",
"gradeid": 8,
"gradename": "初中二年级",
}
];
var oldDataRule = [];
var grade_class_data = [];
oldData.forEach(item => {
oldDataRule[item.gradeid] = oldDataRule[item.gradeid] || [];
oldDataRule[item.gradeid].push(item);
})
for (var key in oldDataRule) {
var obj = { children: [] };
obj.value = key
obj.label = oldDataRule[key][0].gradename
for (var rs in oldDataRule[key]) {
obj.children.push({
value: oldDataRule[key][rs].classid,
label: oldDataRule[key][rs].gradename + oldDataRule[key][rs].classname,
});
}
grade_class_data.push(obj)
}
console.log(grade_class_data);
// 结果为:
// [{"children":[{"value":219,"label":"初中一年级(01)班"},{"value":224,"label":"初中一年级(02)班"}],"value":"7","label":"初中一年级"},{"children":[{"value":228,"label":"初中二年级(08)班"}],"value":"8","label":"初中二年级"}]