2

次のようにアクセスする必要がある 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 の両方で機能するソリューションを希望します。

4

3 に答える 3

2

次のように、オブジェクトを動的に構築するオプションがあります。

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/

したがって、変数のリストを配列に入れて関数に渡す必要があります。または、渡された任意の数の引数で機能するように関数を変更することもできます。

于 2013-04-29T14:11:55.937 に答える
0

変更するオブジェクト、葉のプロパティへのパス ( のようなドット区切りの文字列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/

また、同様の質問がここで尋ねられました:パスと値を含む文字列を渡すことで JavaScript オブジェクトを拡張します

于 2013-04-29T14:14:05.070 に答える