JavaScript 扁平树转嵌套树:高效算法实现
function flatToNested(arr) { const map = {}; const result = []; for (const item of arr) { if (item.id in map) { map[item.id] = Object.assign(map[item.id], item); } else { map[item.id] = item; } if (item.pid && item.pid in map) { const parent = map[item.pid]; if (!parent.children) { parent.children = []; } parent.children.push(map[item.id]); } else { result.push(map[item.id]); } } return result; }
原文地址: https://www.cveoy.top/t/topic/lEZj 著作权归作者所有。请勿转载和采集!