如何使用纯 Javascript 或像下划线这样的库动态构建树列表?

How does one dynamically build a treelist using pure Javascript or a library like underscore?

我无法从以下 json

获取输出
`[
 {theLevel:1,displayName: "John Doe1", index:1, parIndex:null },
 {theLevel:1,displayName: "John Doe2", index:2, parIndex:null },
 {theLevel:2,displayName: "John Doe3", index:3, parIndex:1 },
 {theLevel:2,displayName: "John Doe4", index:4, parIndex:1 },
 {theLevel:3,displayName: "John Doe5", index:5, parIndex:2 },
 {theLevel:3,displayName: "John Doe6", index:6, parIndex:2 },
]`

我的预期输出如下:

  [
      {text:"John Doe1", items:[{text:"John Doe3"},{text:"John Doe4"} ]},
      {text: "John Doe2, items:[{text:"John Doe5"},{text:"John Doe6"}]} ]

这是一个解决方案,它对整个数据进行几次迭代以生成一棵树。可以组合其中一些迭代来提高性能,但在这里我将它们保留原样,以便更清楚地了解发生了什么:

  1. 每人加一个child人属性

    _.each(data, function(person){
        _.extend(person, {children: []});
    });
    
  2. 以人物索引为键,人物索引为值创建数据散列

    var people = _.reduce(data, function(memo, person){
        memo[person.index] = person
        return memo;
    }, {} ); 
    

    人object会是这样的:

    {
       1: {theLevel:1,displayName: "John Doe1", index:1, parIndex:null },
       2: {theLevel:1,displayName: "John Doe2", index:2, parIndex:null },
       3: {theLevel:2,displayName: "John Doe3", index:3, parIndex:1 }
       etc.
    }
    
  3. 将每个child加到parent的children中:

    _.each(data, function(person){
        if( !_.isNull(person.parIndex)) people[person.parIndex].children.push(person);
    });
    

    这会给你留下一棵树。

  4. 然后你可以把这棵树变成任何你喜欢的样子。此代码段将生成问题中的输出:

    function isParent (person) {
        return !_.isEmpty(person.children);
    }
    
    var parents = _.filter(people, isParent);
    
    var result = _.map(parents, function(person){
        return {
            text: person.displayName,
            items: _.map(person.children, function(child){
                return { text: child.displayName };
            })
        };
    

我做了以下似乎解决了一个小问题。我得到了一些 children 的空项目数组。如果项目的数组是空的,我宁愿什么都没有。

  1. 添加children和文字属性

    = _.each(results.data, function (entity) {
              _.extend(entity, { text: entity.displayName });
              _.extend(entity, { items: [] });
       });
    
  2. 像以前一样创建哈希

      = _.reduce(results.data, function (memo, entities) {
                        memo[entities.entIndex] = entities;
                        return memo;
                    }, {});
    
  3. 像以前一样将每个 child 添加到 parent

    = _.each(results.data, function (entity) {
        if (!_.isNull(entity.parEntIndex)) ent[entity.parEntIndex].items.push(entity);
                    });
    

    4.

    function isParent (entity) {
                        return !_.isEmpty(entity.items) && entity.theLev == 1;
                    }
    
                    var test = _.filter(combine, isParent);
    
                    var result = _.map(test, function (currentObject) {
                        return _.pick(currentObject,'text','items');
                    });