gpt4 book ai didi

javascript - Lodash 自动生成 TreeView

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:22:29 25 4
gpt4 key购买 nike

我想为我的 React 组件自动生成 TreeView 。我有多个文件,它们都有自己的路径。例如:

  • com/company/model/Main.java
  • com/company/controller/Move.java
  • com/company/controller/Rotate.java
  • com/company/view/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}]
}
]}]
}

我发现这个库将我的路径拆分为一个选项卡: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要自动生成这个但没有成功,你能帮我吗

最佳答案

使用稍作修改的 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));

关于javascript - Lodash 自动生成 TreeView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34965395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com