const addPath = (arr) => { const map = {}; const result = [];

arr.forEach((item) => { map[item.id] = item; item.children = []; });

arr.forEach((item) => { const parent = map[item.parentId]; if (parent) { parent.children.push(item); } else { result.push(item); } });

const setPath = (node, path) => { node.path = path + node.name; node.children.forEach((child) => { setPath(child, node.path + '/'); }); };

result.forEach((item) => { setPath(item, ''); });

return result; };

const newArray = addPath(array); console.log(newArray)

const array = id 1 parentId null name Node 1 id 2 parentId 1 name Node 2 id 3 parentId 1 name Node 3 id 4 parentId 2 name Node 4 id 5 parentId 2 name Node 5 id 6 parentId 3 name Node 6 ;给

原文地址: https://www.cveoy.top/t/topic/hYOw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录