因此,我一直在努力地绕过这个递归函数并获得正确的结果。
const _ = require('lodash');
let config = {
"Main": {
children: {
"Dashboard": "main.dashboard",
"Account": {
children: {
"Settings": "main.account.settings"
}
}
}
},
"Statistics": {
children: {
"Test One": "main.statistics.test.one",
"Test Two": "main.statistics.test.two"
}
}
}
let processNav = (config, parent) => {
let children;
let results = {};
_.forOwn(config, (value, title) => {
var breadcrumb = parent || title;
if (value.children) {
children = processNav(value.children, breadcrumb);
_.assign(results, children);
} else {
results[value] = [breadcrumb, title];
}
});
return results;
};
let breadcrumbs = processNav(config);
console.log(breadcrumbs);
// output
{ 'main.dashboard': [ 'Main', 'Dashboard' ],
'main.account.settings': [ 'Main', 'Settings' ],
'main.statistics.test.two': [ 'Statistics', 'Test Two' ] }
我正在寻找的输出更像这样...
// expected output
{ 'main.dashboard': [ 'Main', 'Dashboard' ],
'main.account.settings': [ 'Main', 'Account', 'Settings' ],
'main.statistics.test.one': [ 'Statistics', 'Test One' ],
'main.statistics.test.two': [ 'Statistics', 'Test Two' ] }
在我发疯之前,有人能帮我解决这个问题吗?
最佳答案
这种方法不使用.lodash
,仅使用普通JS。
let config = { "Main": { children: { "Dashboard": "main.dashboard", "Account": { children: { "Settings": "main.account.settings" } } } }, "Statistics": { children: { "Test One": "main.statistics.test.one", "Test Two": "main.statistics.test.two" } }};
function loop(obj, path, breadcrumbs) {
Object.keys(obj).forEach(k => {
if (obj[k].children) loop(obj[k].children, [...path, k], breadcrumbs);
else breadcrumbs[obj[k]] = [...path, k];
});
}
let breadcrumbs = {};
loop(config, [], breadcrumbs);
console.log(JSON.stringify(breadcrumbs, null, 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 从json菜单对象构建面包屑的递归函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49029805/