所谓的递归函数就是在函数体内调用本函数。使用递归函数一定要注意,处理不当就会进入死循环。
一、这里以json数据多层嵌套,转换数据为例:
获取的数据结构
{
header:{
datlg: "0",
protid: "0x00000032",
redid: "0x00000000"
}
param:{
func: "0x00000004",
itemcount: "1",
item:{
address: "0x00000000",
area: "0x00000082",
address_tree:{
bit: "0",
byte: "0"
}
}
}
}
需要转换为:
{
text: header
children: [
{text:'datlg: 0'},
{text:'protid: 0x00000032'},
{text:'redid: 0x00000000'}
]
}
{
text:param
children: [
{text:'func: 0x00000004'},
{text:'itemcount: 1'},
{
text:'address_tree',
children:[
{
text:'bit: 0',
text:'byte: 0'
}
]
}
]
}
在不确定数据结构嵌套多少层的时候,可以使用递归:
function parseJson(json) {
var paraObj = [];
for (let key in json) {
if(json[key] instanceof Object){
//使用递归调用自己
let objResult = parseJson(json[key]);
let temp = {};
temp.text = key;
temp.children = objResult;
paraObj.push(temp);
} else {
let temp = {};
temp.text = key + ':' + json[key];
paraObj.push(temp);
}
}
return paraObj;
}
二、刚送走一个嵌套,又来了个扁平的数据结构,根据parentId来判断是否存在children
获取的数据结构:
list:[
{
id: 12
name: "流量监测"
parentId: 0
},{
id: 12
name: "数据管理"
parentId: 0
},{
id: 12
name: "安全总览"
parentId: 8
},{
id: 12
name: "工具箱"
parentId: 26
},
]
根据parentId来匹配children
setTreeData(arr) {
// 删除所有 children,以防止多次调用
arr.forEach(function (item) {
delete item.children;
});
let map = {}; // 构建map
arr.forEach(i => {
map[i.id] = i; // 构建以id为键 当前数据为值
});
let treeData = [];
arr.forEach(child => {
const mapItem = map[child.parentId]; // 判断当前数据的parent_id是否存在map中
if (mapItem) { // 存在则表示当前数据不是最顶层数据
// 注意: 这里的map中的数据是引用了arr的它的指向还是arr,当mapItem改变时arr也会改变,踩坑点
(mapItem.children || ( mapItem.children = [] )).push(child); // 这里判断mapItem中是否存在children, 存在则插入当前数据, 不存在则赋值children为[]然后再插入当前数据
} else { // 不存在则是组顶层数据
treeData.push(child);
}
});
return treeData;
},
第一次使用,欢迎各位多多指点和补充.......