javascript - 从祖先数据构建嵌套列表?

标签 javascript algorithm tree

给定结构:

{
    id: 'id-1',
    name: 'name1',
    ancestors: []
},{
    id: 'id-2',
    name: 'name2',
    ancestors: []
},{
    id: 'id-3',
    name: 'name3',
    ancestors: ['id-1']
},{
    id: 'id-4',
    name: 'name4',
    ancestors: ['id-3', 'id-1']
}
  • 假设它们没有以任何有意义的方式排序。
  • 祖先字段是一个数组,显示了到顶层的路径。

构建嵌套列表 (ul) 的最有效方法是什么?

我的第一个想法是递归方法,但这似乎很麻烦,因为它会重复搜索整个列表。因为这将是一个在浏览器中运行的 javascript 解决方案,可能会出现问题。

最佳答案

您可以构建一棵树,然后呈现一个嵌套列表。

function getTree(data) {
    var o = {};
    data.forEach(function (a) {
        var parent = a.ancestors[0];
        if (o[a.id] && o[a.id].children) {
            a.children = o[a.id].children;
        }
        o[a.id] = a;
        o[parent] = o[parent] || {};
        o[parent].children = o[parent].children || [];
        o[parent].children.push(a);
    });
    return o.undefined.children;
}

function buildList(tree, target) {
    var ul = document.createElement('ul');
    tree.forEach(o => {
        var li = document.createElement('li');
        li.appendChild(document.createTextNode(o.name));
        buildList(o.children || [], li);
        ul.appendChild(li);
    });
    target.appendChild(ul);
}

var data = [{ id: 'id-1', name: 'name1', ancestors: [] }, { id: 'id-2', name: 'name2', ancestors: [] }, { id: 'id-3', name: 'name3', ancestors: ['id-1'] }, { id: 'id-4', name: 'name4', ancestors: ['id-3', 'id-1'] }],
    tree = getTree(data);

console.log(tree);
buildList(tree, document.body);

关于javascript - 从祖先数据构建嵌套列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49982245/

相关文章:

java - Java中的复制算法

javascript - 在 Node.js 中构建多分支树时的性能问题

c - C 中的递归目录复制

javascript - 对于移动屏幕,如何从上到下移动一个 div?

javascript - 使用 Bower 编程 API 强制最新

javascript - 单击带有 anchor #的链接不会转到页面顶部

javascript - 尝试对简单对象执行 JSON.parse 时出现 "Unexpected token"错误

arrays - 排序算法与完全排序的总比较

c# - 如何在列表中搜索距离小于 F 到 P 的项目而不搜索整个列表?

tree - 在 lisp 中创建一棵树