gpt4 book ai didi

javascript - 从 json 菜单对象构建面包屑的递归函数

转载 作者:行者123 更新时间:2023-12-03 02:24:05 25 4
gpt4 key购买 nike

所以我一直在努力理解这个递归函数并获得正确的结果。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com