2016-01-23 49 views
1

我想爲我的反應組件自動生成樹視圖。我有自己的路徑多個文件。對於exmple:Lodash自動生成樹視圖

  • COM /公司/模型/ Main.java
  • COM /公司/控制器/ Move.java
  • COM /公司/控制器/ Rotate.java
  • COM /公司/視圖/Watch.java

的目標是有一個對象的數據看起來像這樣:

var data = { 
    name: com, 
     children: [{name: company, 
        children: [ 
        {name: model, 
        children: [{name: Main.java}] 
        }, 
        {name: controller, 
        children: [{name: Move.java},{name: Rotate.java}] 
        }, 
        {name: view, 
        children: [{name: Watch.java}] 
        } 
       ]}] 
} 

我發現這個lib添加到我的道路被劃分爲標籤:https://nodejs.org/api/path.html

像這樣:

var path = com/company/model/Main.java ; 
var dirname = path.dirname(path); // => « com/company/model » 
var folders = dirname.split(path.sep); // => folders = [‘com’,’compagny’,’model’] 

我試圖用lodash https://lodash.com/docs 爲了不更迭自動生成這個你能幫助我,請

回答

4

使用稍微修改後的版本this answer

var _ = require('lodash'); 
var path = require('path'); 

var paths = [ 
    'com/company/model/Main.java', 
    'com/company/controller/Move.java', 
    'com/company/controller/Rotate.java', 
    'com/company/view/Watch.java' 
]; 

// build input data from the paths 
// { 
//  "lvl0": "com", 
//  "lvl1": "company", 
//  "lvl2": "model", 
//  "name": "Main.java", 
//  "path": "com/company/model/Main.java" 
// } 
var data = paths.map(function (el) { 
    // var folders = path.dirname(el).split(path.sep); 
    var folders = path.dirname(el).split('/'); 
    var obj = {}; 
    for (var i = 0; i < folders.length; i++) { 
     obj['lvl' + i] = folders[i]; 
    } 
    obj.name = path.basename(el); 
    obj.path = el; 
    return obj; 
}); 

// add a new function to lodash 
_.mixin({ 
    groupByMulti: function (obj, values, context) { 
     if (!values.length) return obj; 
     var byFirst = _.groupBy(obj, _.head(values), context); 
     for (var prop in byFirst) { 
      byFirst[prop] = _.groupByMulti(byFirst[prop], _.tail(values), context); 
     } 
     byFirst = _.map(byFirst, function (rows, key) { 
      return { name: key, children: rows }; 
     }); 
     return byFirst; 
    } 
}); 

var out = _.groupByMulti(data, ['lvl0', 'lvl1', 'lvl2'])[0]; 
console.log(JSON.stringify(out, null, 3)); 
+0

非常感謝:) – fandro