javascript - convert list of slugs into json in Javascript
问题描述
I am looking for a javascript function or npm package, which converts list of slugs into a json.
for example this is an input:
const data = [
"/docs/faq.md",
"/docs/index.md",
"/docs/what.md",
"/docs/Tutorials/how-to-buy.md",
"/docs/Tutorials/how-to-store.md",
"/docs/guide.md",
"/docs/Tutorials/analysis.md",
"/docs/Tutorials/index.md",
"/docs/Tutorials/tutorial.md",
"/docs/Tutorials/understanding.md",
"/docs/start.md",
];
and this should be the output:
const output = {
docs: {
children: [
{ title: "index.md" },
{ title: "faq.md" },
{ title: "what.md" },
{
Tutorials: {
children: [
{ title: "index.md" },
{ title: "how-to-buy.md" },
{ title: "how-to-store.md" },
{ title: "analysis.md" },
{ title: "tutorial.md" },
{ title: "understanding.md" },
],
},
},
{ title: "guide.md" },
{ title: "start.md" },
],
},
};
another example:
const data = [
"faq.md",
"index.md",
"/docs/what.md",
"/docs/Tutorials/how-to-buy.md",
"/docs/Tutorials/how-to-store.md",
"/docs/guide.md",
"/docs/Tutorials/analysis.md",
"/docs/Tutorials/index.md",
"/docs/Tutorials/tutorial.md",
"/docs/Tutorials/understanding.md",
"/docs/start.md",
];
and output:
const output = {
children: [
{ title: "index.md" },
{ title: "faq.md" },
{
docs: {
children: [
{ title: "what.md" },
{
Tutorials: {
children: [
{ title: "index.md" },
{ title: "how-to-buy.md" },
{ title: "how-to-store.md" },
{ title: "analysis.md" },
{ title: "tutorial.md" },
{ title: "understanding.md" },
],
},
},
{ title: "guide.md" },
{ title: "start.md" },
],
},
},
],
};
I am not sure if a similar solution is available on Github or npm.
解决方案
Loop your array, split on /
and then just put elements in it's places:
const data = [
"/root-node.md",
"/docs/faq.md",
"/docs/index.md",
"/docs/what.md",
"/docs/Tutorials/how-to-buy.md",
"/docs/Tutorials/how-to-store.md",
"/docs/guide.md",
"/docs/Tutorials/analysis.md",
"/docs/Tutorials/index.md",
"/docs/Tutorials/tutorial.md",
"/docs/Tutorials/understanding.md",
"/docs/start.md",
];
var output = [];
for (var i = 0; i < data.length; i++) {
let parts = data[i].split('/');
let current = output;
for (var j = 1; j < parts.length - 1; j++) {
let found = false;
for (var k = 0; k < current.length; k++) {
if (typeof current[k][parts[j]] !== 'undefined') {
found = true;
current = current[k][parts[j]];
break;
}
}
if (!found) {
let newRow = {}
newRow[parts[j]] = []
current.push(newRow)
current = current[current.length - 1][parts[j]];
}
}
current.push({title: parts[parts.length - 1]});
}
console.log(output)
推荐阅读
- python - python 继续运行以前的模块而不是我想运行的模块?
- c++11 - 为什么允许复制对象的单例设计模式甚至复制构造函数和赋值运算符都是私有的?
- scikit-learn - AWS SageMaker 最低配置
- javascript - 如何仅使用一个变量声明对数组进行正确排序并删除 JavaScript 中的重复项?
- typescript - 打字稿:返回时在泛型对象中强制执行泛型类型的函数?
- angular - 通用类型'观察者
' 需要 2 个类型参数。@firebase/app-types/private.d.ts - matlab - 如何从 excel 数据中绘制 3D 曲面
- javascript - 如何获取包含表单中所有可用输入标签的列表
- objective-c - 滚动结束时的 UItableview 有一些额外的空间
- python - 对象类型
无法传递给 C 代码 - 虚拟环境