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

In JavaScript, recursively build a dictionary / nested object from a set of arrays

本文关键字:对象 构建 一个 嵌套 字典 一组 JavaScript 数组 递归      更新时间:2023-09-26

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

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

例如

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

成为

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

等等。

我想做的是:

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

我遇到的问题是查看通往所涉房产的任意路径。我不知道如何建立一个多层次的路径到我正在寻找的物业名称。即,当i==0时,

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

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

然后,我没有办法将下一步添加到检查变量中——

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

进一步的排列是行不通的。

我确信我在这里错过了一些愚蠢的东西,但我被卡住了,如果有人知道的话,我会很感激的。

而且,需要注意的是,如果可能的话,我只需要使用jQuery或lodash来实现这一点,如果在纯JS中无法合理实现的话。

简单:

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

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

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>