【问题标题】:Construct hierarchy tree from flat list with child field?从带有子字段的平面列表构造层次结构树?
【发布时间】:2014-12-03 08:47:39
【问题描述】:

我有一个带有子字段的“页面”对象列表。此子字段引用列表中的另一个对象。我想根据这个字段从这个列表中创建一个树层次结构。 我找到了一个解决方案here,但它只有在我有父字段时才有效。这是我的原始列表的样子:

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

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

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

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

【问题讨论】:

    标签: javascript arrays tree hierarchy


    【解决方案1】:

    找到解决办法,使用Underscore.js添加父母,然后使用this solution

    _.each(flat, function (o) {
      o.child.forEach(function (childId) {
        _.findWhere(flat, {id: childId}).parent = o.id;
      });
    });
    

    【讨论】:

      【解决方案2】:

      下面的函数从对象列表构建一棵树。 它对任何格式都不严格。 与您的示例的唯一区别是您提供了 parent 键,而不是 child

      function buildTree(flatList, idFieldName, parentKeyFieldName, fieldNameForChildren) {
          var rootElements = [];
          var lookup = {};
      
          flatList.forEach(function (flatItem) {
            var itemId = flatItem[idFieldName];
            lookup[itemId] = flatItem;
            flatItem[fieldNameForChildren] = [];
          });
      
          flatList.forEach(function (flatItem) {
            var parentKey = flatItem[parentKeyFieldName];
            if (parentKey != null) {
              var parentObject = lookup[flatItem[parentKeyFieldName]];
              if(parentObject){
                parentObject[fieldNameForChildren].push(flatItem);
              }else{
                rootElements.push(flatItem);
              }
            } else {
              rootElements.push(flatItem);
            }
      
          });
      
          return rootElements;
        }
      

      Here is a fiddle 使用您的示例作为输入。

      原文出处comes from this answer

      【讨论】:

        猜你喜欢
        • 2019-03-05
        • 1970-01-01
        • 2010-09-24
        • 2018-02-06
        • 1970-01-01
        • 2018-10-07
        • 2016-11-07
        • 2018-04-13
        • 2013-01-22
        相关资源
        最近更新 更多