从带有子字段的平面列表构造层次树? [英] Construct hierarchy tree from flat list with child field?

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

问题描述

我有一个带有子字段的页面对象列表。该子字段引用列表中的另一个对象。我想基于此字段从此列表创建树层次结构。
我已经在此处找到了解决方案,但是只有在我有父字段的情况下它才有效。列表如下所示:

I have a list of "page" objects with a child field. This child field references another object in the list. I would like to create a tree hierarchy from this list based on this field. I have found a solution here but it works only if I have a parent field.Here is what my original list looks like:

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

我想将其转换为这样的树结构:

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

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

我希望可以调用一个可重用的函数任何时间的任意列表。任何人都知道解决此问题的好方法吗?

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!

推荐答案

使用Underscore.js添加父母,然后使用此解决方案

Found a solution by using Underscore.js to add parents and then use this solution

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

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

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