JS树形数据操作
2022-02-28 23:49 龙恩0707 阅读(836) 评论(0) 编辑 收藏 举报1. 给树形菜单添加一个唯一标识
function renderTreeFunc(data) { let arrs = []; let i = 1; const loopFunc = function(data) { const rets = []; let obj = {}; if (data.length > 0) { data.forEach(item => { const temp = { ...item }; const { nodeName, nodeType } = item; obj = { 'nodeName': nodeName, 'nodeType': nodeType, 'customId': i++, }; if (temp.children && temp.children.length) { temp.children = loopFunc(temp.children); obj['children'] = temp.children; } rets.push(obj); }) } return rets; } if (data && data.length) { arrs = loopFunc(data); } return arrs; } const rets = renderTreeFunc(data); console.log('-----rets----', rets);
2. 根据id获取该节点的所有父节点的对象
function getParentsId(list, id) { for (let i in list) { if (list[i].customId == id) { return [list[i]]; } if (list[i].children) { let node = getParentsId(list[i].children, id); if (node !== undefined) { return node.concat(list[i]); } } } } const newArrs = getParentsId(rets, 3); console.log('----newArrs---', newArrs);
3. 树形菜单添加序号,比如 1.1/1.1.1/1.1.2 这样的。
const setIndex = (data) => { console.log('----初始化数据----', data); let queue = [...data]; let loop = 0; while (queue.length > 0) { loop++ [...queue].forEach((child, i) => { queue.shift() if (loop == 1) { child.customIndex = i + 1 + ""; } if (child.children && child.children.length > 0) { for (let ci = 0; ci < child.children.length; ci++) { child.children[ci].customIndex = child.customIndex + "." + (ci + 1) } queue.push(...child.children) } }) } console.log('---------组装后的数据-----', data); return data; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
2015-02-28 CSS3页面布局方案