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 函数上抛出错误而无法使其工作:
未捕获的类型错误:_.findWhere 不是函数
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);
});
任何帮助将不胜感激!
解决方案
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; }
推荐阅读
- jquery - JQuery 函数仅适用于第一行
- python - python按字符分割与默认分割
- c++ - 以不同方式旋转立方体
- vue.js - 如何将 vue-awesome-swiper 与 slideTo() 一起使用?
- javascript - 在 Hammer.js 中拖放?
- node.js - 在 Angular 中调用外部应用程序
- php - 如何合并两个多维数组并调整现有值?
- codeigniter - 如何纠正codeigniter中payu支付网关的错误?
- azure - 在 HTML 文件中使用 Azure 函数输出
- html - 我不知道为什么在弹性框中我的图像下方有一个空白区域