在JavaScript中,从一组数组中递归地构建字典/嵌套对象

Mat*_*att 2 javascript arrays recursion reduce json

我觉得自己有点虚伪,但我很难找到解决方案.

我有一组数组,我需要使用它们来构建一个JSON-ish对象.

例如

[a]
[a, b]
[a, b, c]
[a, b, d]
[e]
[e, f]
[e, f, g]
Run Code Online (Sandbox Code Playgroud)

{
  a: {
    b: {
      c: {}
      d: {}
    }
  }
  e: {
    f: {
      g: {}
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

等等.

我想做的是:

  1. 实例化一个空对象,Dictionary
  2. 取一个长度为n的任意数组
  3. 迭代数组,这样在数组位置i,如果Dictionary在Dictionary [Array [0]] ... [Array [i]]中没有属性,我将该属性定义为Array [i]:{}

我遇到的问题是查看相关属性的任意路径.我不知道如何构建我正在寻找的属性名称的多级路径.即,当我=== 0时,

var check = Array[i];
typeof Dictionary[check] === 'undefined';
Run Code Online (Sandbox Code Playgroud)

我们会得到预期的行为.但它显然会将整个数组构建为一组平面对象属性(而不是嵌套字典).

我没有办法在check变量中添加下一步-

...
check = check[Array[i+1];

check = Dictionary[check][Array[i+1]]
Run Code Online (Sandbox Code Playgroud)

并且进一步的排列不起作用.

我敢肯定我在这里丢失了一些愚蠢的东西,但我坚持下去,如果有人拥有它,我会很感激.

并且,要注意,如果可能的话,我只需要使用jQuery或lodash,如果它在普通的JS中无法合理地实现.

geo*_*org 5

简单:

lst = [
    ['a'],
    ['a', 'b'],
    ['a', 'b', 'c'],
    ['a', 'b', 'd'],
    ['e'],
    ['e', 'f'],
    ['e', 'f', 'g']
];


tree = {};
lst.forEach(function(item) {
    item.reduce(function(node, chr) {
        return node[chr] || (node[chr] = {});
    }, tree);
});

document.write("<pre>" + JSON.stringify(tree, 0, 3))
Run Code Online (Sandbox Code Playgroud)