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

时间:2018-02-28 12:38:58

标签: javascript recursion lodash

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

apt-get install php7.0-mbstring

service apache2 restart

我正在寻找的输出更像是......

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' ] }

在我发疯之前,有谁可以帮助我解决这个问题?

2 个答案:

答案 0 :(得分:1)

这种方法不使用set /?,只使用普通的JS。

.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"        }    }};

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));

答案 1 :(得分:0)

主要困难是跳过children对象。因此,我在递归模式中包含了一个额外的案例。

如果当前"节点"有一个children属性,它"跳过"它通过无条件地调用下一个递归:

isParent(obj) ? getPaths(obj.children, path, result) : /* ... * /

行动中:



const 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"}}};

const isParent = x => x.children;
const isLeaf = x => typeof x === "string";

const getPaths = (obj, path = [], result = {}) => 
  isParent(obj)
    // The "Skip" case:
    ? getPaths(obj.children, path, result)
    : isLeaf(obj)
      // The *final* case:
      ? Object.assign(result, { [obj]: path })
      // The *recurse* case:
      : Object.keys(obj).reduce(
      	(r, k) => getPaths(obj[k], path.concat(k), r),
        result);
        
console.log(getPaths(config));