我有一个带有父字段的“页面”对象的列表.此父字段引用列表中的另一个对象.我想从这个列表中创建一个树层次结构.
这是我的原始列表的样子:
- [
- {
- id: 1,title: 'home',parent: null
- },{
- id: 2,title: 'about',{
- id: 3,title: 'team',parent: 2
- },{
- id: 4,title: 'company',parent: 2
- }
- ]
我想把它转换成一个这样的树结构:
- [
- {
- id: 1,parent: null,children: [
- {
- id: 3,parent: 2
- },{
- id: 4,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) {
- lookup[obj[parentAttr]][childrenAttr].push(obj);
- } else {
- treeList.push(obj);
- }
- });
- return treeList;
- };