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

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

问题描述

我有一个字段页对象的列表。该父字段引用另一对象中的列表中。我想创建基于此领域此列表中的树状分层结构。

下面是我最初的名单是什么样子:

  [
  {
    ID:1,
    标题:'家',
    父:空
  },
  {
    ID:2,
    标题:关于,
    父:空
  },
  {
    ID:3,
    标题:团队,
    父:2
  },
  {
    ID:4,
    标题:公司,
    父:2
  }
]

我想它转换成一个树状结构是这样的:

  [
  {
    ID:1,
    标题:'家',
    父:空
  },
  {
    ID:2,
    标题:关于,
    父:空,
    儿童:
      {
        ID:3,
        标题:团队,
        父:2
      },
      {
        ID:4,
        标题:公司,
        父:2
      }
    ]
]

我希望的一个可重用的功能,我可以打电话对任意列表中的任何时间。任何人都知道的来处理这个好办法?任何帮助或建议将不胜AP preciated!


解决方案

 函数treeify(列表,idAttr,parentAttr,childrenAttr){
    如果(!idAttr)idAttr ='ID';
    如果(parentAttr!)parentAttr =父;
    如果(childrenAttr!)childrenAttr ='孩子';    VAR树形列表= [];
    变种查找= {};
    list.forEach(函数(OBJ){
        查找[OBJ [idAttr] = OBJ;
        物镜[childrenAttr] = [];
    });
    list.forEach(函数(OBJ){
        如果(OBJ [parentAttr]!= NULL){
            查找[物镜[parentAttr]] [childrenAttr] .push(物镜);
        }其他{
            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) {
            lookup[obj[parentAttr]][childrenAttr].push(obj);
        } else {
            treeList.push(obj);
        }
    });
    return treeList;
};

Fiddle

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

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