下划线分隔字符串的树结构

时间:2018-12-07 10:07:14

标签: javascript

美好的一天,

我需要这样转换字符串:

Process1_Cat1_Cat2_Value1
Process1_Cat1_Cat2_Value2
Process2_Cat1_Cat2_Value1

放入嵌套数组,例如:

 var d = [{
        text: 'Process1',
        children: [{
            text: 'Cat1',
            children: [{
                text: 'Cat2',
                children: [{
                    text: 'Value1'
                },
                {
                    text: 'Value2'
                }]
            }]
        }]
    },

    {
        text: 'Process2',
        children: [{
            text: 'Cat1',
            children: [{
                text: 'Cat2',
                children: [{
                    text: 'Value1'
                }]
            }]
        }]
    },


];

我需要这样做的原因是利用树形视图显示我的数据:

https://www.npmjs.com/package/bootstrap-tree-view

我查看了以下解决方案,但由于lowdash库在findWhere函数上抛出错误而无法使它工作:

  

未捕获的TypeError:_.find哪里没有函数

http://brandonclapp.com/arranging-an-array-of-flat-paths-into-a-json-tree-like-structure/

请参见下面的代码:

function arrangeIntoTree(paths, cb) {
    var tree = [];

    // This example uses the underscore.js library.
    _.each(paths, function(path) {

        var pathParts = path.split('_');
        pathParts.shift(); // Remove first blank element from the parts array.

        var currentLevel = tree; // initialize currentLevel to root

        _.each(pathParts, function(part) {

            // check to see if the path already exists.
            var existingPath = _.findWhere(currentLevel, {
                name: part
            });

            if (existingPath) {
                // The path to this item was already in the tree, so don't add it again.
                // Set the current level to this path's children
                currentLevel = existingPath.children;
            } else {
                var newPart = {
                    name: part,
                    children: [],
                }

                currentLevel.push(newPart);
                currentLevel = newPart.children;
            }
        });
    });

    cb(tree);
}


arrangeIntoTree(paths, function(tree) {
    console.log('tree: ', tree);
});

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

您可以通过在实际级别上查找text来使用迭代。如果找不到,请创建一个新对象。返回下一级的子数组,直到嵌套最多的数组为止。然后添加叶子对象。

var data = ['Process1_Cat1_Cat2_Value1', 'Process1_Cat1_Cat2_Value2', 'Process2_Cat1_Cat2_Value1'],
    result = data.reduce((r, s) => {
        var keys = s.split('_'),
            text = keys.pop();
    
        keys
            .reduce((q, text) => {
                var temp = q.find(o => o.text === text);
                if (!temp) {                    
                    q.push(temp = { text, children: [] });
                }
                return temp.children;
            }, r)
            .push({ text });
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }