【问题标题】:In JavaScript, recursively build a dictionary / nested object from a set of arrays在 JavaScript 中,从一组数组递归构建字典/嵌套对象
【发布时间】:2015-04-11 14:14:02
【问题描述】:

我觉得自己有点像个傻瓜,但我正在努力寻找解决方案。

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

例如

[a]
[a, b]
[a, b, c]
[a, b, d]
[e]
[e, f]
[e, f, g]

变成

{
  a: {
    b: {
      c: {}
      d: {}
    }
  }
  e: {
    f: {
      g: {}
    }
  }
}

等等。

我想做的是:

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

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

var check = Array[i];
typeof Dictionary[check] === 'undefined';

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

然后我没有办法将下一步添加到 check 变量中 --

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

check = Dictionary[check][Array[i+1]]

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

我确定我在这里遗漏了一些愚蠢的东西,但我被困住了,如果有人知道的话,我将不胜感激。

并且,需要注意的是,如果可能的话,我只需要使用 jQuery 或 lodash 来执行此操作,如果在普通 JS 中无法合理实现的话。

【问题讨论】:

    标签: javascript arrays json recursion reduce


    【解决方案1】:

    你有一个更简洁的答案,但我已经写了......

    var arrs = [
        ['a'],
        ['a', 'b'],
        ['a', 'b', 'c'],
        ['a', 'b', 'd'],
        ['e'],
        ['e', 'f'],
        ['e', 'f', 'g'],
        ['e', 'f', 'g', 'h', 'i'],
        ['e', 'f', 'g', 'h', 'j']
    ];
    
    var dictionary = {};
    
    arrs.forEach(function (item) {
        addArray(dictionary, item);
    });
    
    document.getElementById("output").innerText = JSON.stringify(dictionary, null, 3);
    
    function addArray(dic, arr) {
        arr.forEach(function (item) {
            dic = addNode(dic, item);
        });
        return dic;
    }
    
    function addNode(node, item) {
        return node[item] || (node[item] = {});
    }
    <pre id="output"></pre>

    【讨论】:

    • Georg 的回答较短,但您的冗长很有帮助,感谢您的发布。
    【解决方案2】:

    简单:

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

    【讨论】:

    • 谢谢。我确定这是我在消隐的愚蠢行为。
    • 请注意,出于某种原因,IE10 没有为数组实现 .reduce()。虽然能够使其与 Lodash 一起使用。
    • @Matt:这很奇怪,因为它在 IE9 中运行良好。
    • 同意,根据各种定义网站,看起来应该没有问题。
    猜你喜欢
    • 2017-07-02
    • 2019-02-08
    • 2021-03-04
    • 1970-01-01
    • 2014-07-17
    • 2019-10-12
    • 1970-01-01
    • 2022-01-04
    • 2018-04-20
    相关资源
    最近更新 更多