目前,我有這個物件
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' },
],
},
],
}];
在這種情況下,我怎樣才能遞回地制作結構?我已經閱讀了 lodash 庫檔案,但我找不到一個很好的組合來處理這個問題。
我能得到任何提示嗎?
uj5u.com熱心網友回復:
如果值為物件,您可以創建遞回函式并再次運行它,或者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://www.uj5u.com/shujuku/512800.html
