使用lodash.js将平面数组转换为树形数组

4


我正在尝试将一个扁平的数组转换为树形数组,因为我将在jsTree中使用这些数据。另外,我需要将键名从“Name”转换为“text”。
我想使用lodash.js,但我对lodash真的很新手。我搜索了解决方案,但没有找到适合我的情况。
所以你能帮忙吗?我的扁平数组数据如下:

[
    {
        Id:1,
        Name: 'name1',
        Parent: 0
    },
    {
        Id:2,
        Name: 'name2',
        Parent: 1
    },
    {
        Id:3,
        Name: 'name3',
        Parent: 2
    },
    {
        Id:4,
        Name: 'name4',
        Parent: 1
    },
    {
        Id:5,
        Name: 'name5',
        Parent: 1
    },
    {
        Id:6,
        Name: 'name6',
        Parent: 5
    }
]

我想要像这样的树形数据:

{
    "id": 1, 
    "text" : "name1", 
    "children" : [
        { 
            "id": 2, 
            "text" : "name2", 
            "children" : [{
                "id": 3,
                "text": "name3"
            }] 
        },
        { 
            "id": 4, 
            "text" : "name4" 
        },
        { 
            "id": 5, 
            "text" : "name5",
            "children" : [{
                "id": 6,
                "text": "name6"
            }]  
        }
    ]
}

谢谢您提前的支持。

数据按照父级排序了吗? - Nina Scholz
@NinaScholz 是的,我们可以这样想。 - baris usanmaz
4个回答

2
这是一个针对未排序数据的纯JavaScript提案。

var data = [{ Id: 1, Name: 'name1', Parent: 0 }, { Id: 2, Name: 'name2', Parent: 1 }, { Id: 3, Name: 'name3', Parent: 2 }, { Id: 4, Name: 'name4', Parent: 1 }, { Id: 5, Name: 'name5', Parent: 1 }, { Id: 6, Name: 'name6', Parent: 5 }],
    tree = function (data, root) {
        var r;
        data.forEach(function (a) {
            this[a.Id] = { id: a.Id, text: a.Name, children: this[a.Id] && this[a.Id].children };
            if (a.Parent === root) {
                r = this[a.Id];
            } else {
                this[a.Parent] = this[a.Parent] || {};
                this[a.Parent].children = this[a.Parent].children || [];
                this[a.Parent].children.push(this[a.Id]);
            }
        }, Object.create(null));
        return r;
    }(data, 0);

document.write('<pre>' + JSON.stringify(tree, 0, 4) + '</pre>');


1

如果您不确定子元素是否可以出现在父元素之前,则可以使用此代码:

var t = [{ Id: 1, Name: 'name1', Parent: 0 }, { Id: 2, Name: 'name2', Parent: 1 }, { Id: 3, Name: 'name3', Parent: 2 }, { Id: 4, Name: 'name4', Parent: 1 }, { Id: 5, Name: 'name5', Parent: 1 }, { Id: 6, Name: 'name6', Parent: 5 }];

var elements = [];
t.forEach(function(element) {
 elements[element.Id] = {
  id: element.Id,
  text: element.Name,
  parent: element.Parent,
  children: []
 }
});

elements.forEach(function(element) {
 elements[element.parent] && elements[element.parent].children.push(element);
 delete element.parent;
})

document.write(['<pre>', JSON.stringify(elements[1], 0, 3), '</pre>'].join(''));


1
下面的函数从对象列表构建一棵树。它不局限于任何格式。
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;
  }

这里有一个 jsfiddle,使用你的示例作为输入。

原始代码 来自这个答案


0

类似于

return _(data).map(function(val) { val.children = []; })
.map(function(val, key) {
    data[val.parent].children.push(val);
});

滥用数组索引。您可能需要先从源数据构建一个辅助映射,从Idindex

这只是使用Array.map的基本用法,因此不需要lodash来解决此问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接