目前,我有一个对象
const path ={
"posts": {
"backend": {
"a.mdx": "./pages/posts/backend/a.mdx"
},
"frontend": {},
"retrospective": {
"b.mdx": "./pages/posts/retrospective/b.mdx",
"c.mdx": "./pages/posts/retrospective/c.mdx",
"d.mdx": "./pages/posts/retrospective/d.mdx"
}
}
}我想要的是。
const path = [{
title: 'posts',
sub: [
{
title: 'backend',
sub: [
{ title: 'a.mdx', path: './pages/posts/backend/a.mdx' },
],
},
{
title: 'frontend',
sub: [],
},
{
title: 'retrospective',
sub: [
{ title: 'b.mdx', path: './pages/posts/retrospective/b.mdx' },
{ title: 'c.mdx', path: './pages/posts/retrospective/c.mdx' },
{ title: 'd.mdx', path: './pages/posts/retrospective/d.mdx' },
],
},
],
}];在这种情况下,如何使结构递归?我看过房客图书馆的文件,但我找不到一个很好的组合来处理这个问题。
能给我点提示吗?
发布于 2022-10-06 13:30:37
如果值是object,则可以创建递归函数并再次运行它;如果值是字符串,则可以设置path。检查内嵌注释:
// Object
const path = {
"posts": {
"backend": {
"a.mdx": "./pages/posts/backend/a.mdx"
},
"frontend": {},
"retrospective": {
"b.mdx": "./pages/posts/retrospective/b.mdx",
"c.mdx": "./pages/posts/retrospective/c.mdx",
"d.mdx": "./pages/posts/retrospective/d.mdx"
}
}
};
// Recursive function
const recursiveFn = data => {
// Set array for function runtime result
const res = [];
// Iterate through keys in your object
for(const key in data) {
// If value is object, process it
// again in recursion
if(typeof data[key] === 'object' && data[key] !== null) {
res.push({
"title": key,
"sub": recursiveFn(data[key])
});
// If value is string
} else if(typeof data[key] === 'string') {
res.push({
"title": key,
"path": data[key]
});
}
}
// Return result
return res;
}
// Run test
console.log(recursiveFn(path));
https://stackoverflow.com/questions/73974374
复制相似问题