从带有父字段的平面列表构建层次结构树? [英] Construct hierarchy tree from flat list with parent field?

查看:24
本文介绍了从带有父字段的平面列表构建层次结构树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我的原始列表的样子:

<预><代码>[{编号:1,标题:'家',父级:空},{编号:2,title: '关于',父级:空},{编号:3,title: '团队',家长:2},{编号:4,title: '公司',家长:2}]

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

<预><代码>[{编号:1,标题:'家',父级:空},{编号:2,title: '关于',父级:空,孩子们: [{编号:3,title: '团队',家长:2},{编号:4,title: '公司',家长:2}]]

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

解决方案

function treeify(list, idAttr, parentAttr, childrenAttr) {if (!idAttr) idAttr = 'id';if (!parentAttr) parentAttr = 'parent';if (!childrenAttr) childrenAttr = 'children';var treeList = [];var 查找 = {};list.forEach(function(obj) {查找[obj[idAttr]] = obj;obj[childrenAttr] = [];});list.forEach(function(obj) {如果 (obj[parentAttr] != null) {if (lookup[obj[parentAttr]] !== undefined) {查找[obj[parentAttr]][childrenAttr].push(obj);} 别的 {//console.log('缺少父数据:' + obj[parentAttr]);treeList.push(obj);}} 别的 {treeList.push(obj);}});返回树列表;};

小提琴

I have a list of "page" objects with a parent field. This parent field references another object in the list. I would like to create a tree hierarchy from this list based on this field.

Here is what my original list looks like:

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

I would like to convert it into a tree structure like this:

[
  {
    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
      }
    ]
]

I was hoping for a reusable function that I can call against an arbitrary list any time. Anyone know of a good way to handle this? Any help or advice would be greatly appreciated!

解决方案

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

这篇关于从带有父字段的平面列表构建层次结构树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆