一维JSON转树结构
作者:互联网
const treeFormat = (arr: any) => { let map: any = {}; // 构建map // 构建以id为键 当前数据为值 arr.forEach((item: any) => { item["children"] = []; map[item['id']] = item; }); const res: any = { data:[], other:[] }; arr.forEach((child: any) => { const mapItem = map[child['parentId']]; // 判断当前数据的id是否存在map中; if (mapItem) { // 存在则表示当前数据不是最顶层数据 (mapItem["children"] || (mapItem["children"] = [])).push(child); } else { // 不存在则是组顶层数据 child['parentId'] === 0 ? res.data.push(child):res.other.push(child) } }); map = null; return res; }
标签:mapItem,map,树结构,res,item,JSON,一维,child,any 来源: https://www.cnblogs.com/y-shmily/p/16650645.html