Assume that I need a JavaScript dictionary (object/ associative array) which I need to access as follows:
var value = dict[foo][bar][buz][qux]; // this could go on
Which is the best way to initialize this dictionary? The only way I can think of is:
// 'foo', 'bar', 'baz', 'qux' are variables
var dict = {};
dict[foo] = {};
dict[foo][bar] = {};
dict[foo][bar][buz] = {};
dict[foo][bar][buz][qux] = value;
Alternatively, is there a better way of achieving the same results? I would prefer a solution that works both in browsers and Node.js.
An option is to build the object dynamically, like:
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));
DEMO: http://jsfiddle.net/BnkPz/
So your list of variables would have to be put into an array and passed to the function, or the function could modified to work with any number of passed arguments.