接受的答案对我的研究非常有帮助,但是,我必须在心里解析 id 参数,我理解这会使函数更灵活,但对于算法新手来说可能有点难以推理。
如果其他人遇到这个困难,这里的代码基本相同,但可能更容易理解:
const treeify = (arr, pid) => {
const tree = [];
const lookup = {};
// Initialize lookup table with each array item's id as key and
// its children initialized to an empty array
arr.forEach((o) => {
lookup[o.id] = o;
lookup[o.id].children = [];
});
arr.forEach((o) => {
// If the item has a parent we do following:
// 1. access it in constant time now that we have a lookup table
// 2. since children is preconfigured, we simply push the item
if (o.parent !== null) {
lookup[o.parent].children.push(o);
} else {
// no o.parent so this is a "root at the top level of our tree
tree.push(o);
}
});
return tree;
};
它与一些 cmets 接受的答案相同,用于解释发生了什么。这是一个用例,它会根据级别生成一个 div 列表,其中包含内联 marginLeft 缩进的页面:
const arr = [
{id: 1, title: 'All', parent: null},
{id: 2, title: 'Products', parent: 1},
{id: 3, title: 'Photoshop', parent: 2},
{id: 4, title: 'Illustrator', parent: 2},
{id: 4, title: 'Plugins', parent: 3},
{id: 5, title: 'Services', parent: 1},
{id: 6, title: 'Branding', parent: 5},
{id: 7, title: 'Websites', parent: 5},
{id: 8, title: 'Pen Testing', parent: 7}];
const render = (item, parent, level) => {
const div = document.createElement('div');
div.textContent = item.title;
div.style.marginLeft = level * 8 + 'px';
parent.appendChild(div);
if (item.children.length) {
item.children.forEach(child => render(child, div, ++level));
}
return parent;
}
const fragment = document.createDocumentFragment();
treeify(arr)
.map(item => render(item, fragment, 1))
.map(frag => document.body.appendChild(frag))
如果你想运行 Codepen:https://codepen.io/roblevin/pen/gVRowd?editors=0010
在我看来,这个解决方案的有趣之处在于,查找表使用项目的 ID 作为键保持平坦,并且只有根对象被推入结果树列表。然而,由于 JavaScript 对象的引用性质,根有它的孩子,孩子有他们的孩子,等等,但它本质上是从根连接起来的,因此是树状的。