javascript - 从具有父字段的平面列表构造层次树?

标签 javascript arrays json tree hierarchy

<分区>

我有一个带有 parent 字段的“页面”对象列表。此父字段引用列表中的另一个对象。我想根据这个字段从这个列表创建一个树层次结构。

这是我的原始列表:

[
  {
    id: 1,
    title: 'home',
    parent: null
  },
  {
    id: 2,
    title: 'about',
    parent: null
  },
  {
    id: 3,
    title: 'team',
    parent: 2
  },
  {
    id: 4,
    title: 'company',
    parent: 2
  }
]

我想把它转换成这样的树结构:

[
  {
    id: 1,
    title: 'home',
    parent: null
  },
  {
    id: 2,
    title: 'about',
    parent: null,
    children:  [
      {
        id: 3,
        title: 'team',
        parent: 2
      },
      {
        id: 4,
        title: 'company',
        parent: 2
      }
    ]
]

我希望有一个可重用的函数,我可以随时针对任意列表调用它。有人知道处理这个问题的好方法吗?任何帮助或建议将不胜感激!

最佳答案

function treeify(list, idAttr, parentAttr, childrenAttr) {
    if (!idAttr) idAttr = 'id';
    if (!parentAttr) parentAttr = 'parent';
    if (!childrenAttr) childrenAttr = 'children';

    var treeList = [];
    var lookup = {};
    list.forEach(function(obj) {
        lookup[obj[idAttr]] = obj;
        obj[childrenAttr] = [];
    });
    list.forEach(function(obj) {
        if (obj[parentAttr] != null) {
            if (lookup[obj[parentAttr]] !== undefined) {
                lookup[obj[parentAttr]][childrenAttr].push(obj);
            } else {
                 //console.log('Missing Parent Data: ' + obj[parentAttr]);
                 treeList.push(obj);
            }               
        } else {
            treeList.push(obj);
        }
    });
    return treeList;
};

Fiddle

关于javascript - 从具有父字段的平面列表构造层次树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22367711/

相关文章:

python - Flask Python REST API 在接收 POST 时设置可选 JSON 参数

javascript - 在键入时有条件地从字符串中删除特殊字符

javascript - 无法从 Javascript addEventListener 方法调用 jQuery POST 请求

javascript - 检查帖子是否在收藏夹列表中的最佳方法

java - 使用泛型数组时抛出异常

java - 如何使用java通过id查找json节点并返回该节点?

javascript - foreach() 触发 'Uncaught RangeError: Maximum call stack size exceeded'

javascript - Jquery 每个函数不适用于字符串索引数组

php - 数组 PHP 到 JavaScript?

jquery - 通过 WCF 数据服务使用 OData 时出现 JSON 错误