【问题标题】:Preferred way of creating "dictionary of dictionaries" in JavaScript在 JavaScript 中创建“字典中的字典”的首选方式
【发布时间】:2013-04-23 04:51:44
【问题描述】:

假设我需要一个 JavaScript 字典(对象/关联数组),我需要按如下方式访问它:

var value = dict[foo][bar][buz][qux]; // this could go on

初始化这个字典的最好方法是什么?我能想到的唯一方法是:

// 'foo', 'bar', 'baz', 'qux' are variables
var dict = {};
dict[foo] = {};
dict[foo][bar] = {};
dict[foo][bar][buz] = {};
dict[foo][bar][buz][qux] = value;

或者,是否有更好的方法来实现相同的结果?我更喜欢在浏览器和 Node.js 中都可以使用的解决方案。

【问题讨论】:

    标签: javascript object dictionary initialization associative-array


    【解决方案1】:

    使用JSON.parse:

    var dict = JSON.parse('{ "' + foo + '": { "' + bar + '": { "' + buz + '": { "' + qux + '": "value"}}}}');
    

    【讨论】:

    • @adrianp 您应该编辑原始问题以包含该要求。
    【解决方案2】:

    您可以创建一个函数,该函数接受要修改的对象、叶子属性的路径(一个点分隔的字符串,如foo + '.' + bar + '.' + buz + '.' + qux)和值,然后让它循环并为您完成工作:

    var foo = 'foo',
        bar = 'bar',
        buz = 'buz',
        qux = 'qux',
        path = foo + '.' + bar + '.' + buz + '.' + qux,
        dict = {};
    
    createNestedProperty(dict, path, 10);
    console.log(dict);
    
    function createNestedProperty(dict, path, value) {
        var pathArray = path.split('.'),
            current;
        while(pathArray.length) {
            current = pathArray.shift();
            if(!dict.hasOwnProperty(current)) {
                if(pathArray.length) {
                    dict[current] = {};  
                // last item
                } else {
                    dict[current] = value;     
                }
            }
        }
    }
    

    http://jsfiddle.net/NuqtM/

    此外,这里也提出了类似的问题:Extend a JavaScript object by passing a string with the path and a value

    【讨论】:

    • 虽然这个解决方案可以发挥作用,但我有点担心它的“可维护性”(对于继承我项目的任何人)。
    【解决方案3】:

    一个选项是动态构建对象,例如:

    var vals = [1, 2, 3, 4];
    
    function createObject(arr) {
        var obj = {};
        var mod = obj;
        for (var i = 0, j = arr.length; i < j; i++) {
            if (i === (j - 1)) {
                mod.value = arr[i];
            } else {
                mod[arr[i]] = {};
                mod = mod[arr[i]];
            }
        }
        return obj;
    }
    
    console.log(createObject(vals));
    

    演示: http://jsfiddle.net/BnkPz/

    所以你的变量列表必须放入一个数组并传递给函数,或者可以修改函数以使用任意数量的传递参数。

    【讨论】:

    • 这似乎是最好的解决方案,我可能会接受它。
    • @adrianp 接受最适合您的方式。你最初的问题有点令人困惑,所以只要一个解决方案对你有用并且效果很好,那就去吧。如果您想了解有关解决方案的更多信息,请向任何人提问
    猜你喜欢
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 2019-08-07
    • 2019-01-16
    • 1970-01-01
    • 2021-06-25
    相关资源
    最近更新 更多