Just use a loop that iterates namesand grabs the next nested object for the current name. Either false or the end of the array should stop the loop.
var obj = options;
var i = 0;
while (obj && i < names.length)
obj = obj[names[i++]];
Or just use .reduce()
names.reduce(function(obj, name) {
return obj && obj[name];
}, options);
, , , .
function toPropertyIn(obj, name) {
return obj && obj[name];
}
names.reduce(toPropertyIn, options);
/:
function nestedProp(obj, names, value) {
if (arguments.length > 1)
var setProp = names.pop();
var res = names.reduce(function(obj, name) {
return obj && obj[name];
}, options);
if (res && setProp !== undefined)
res[setProp] = value;
else
return res;
}
nestedProp(options, names, "foo");
var val = nestedProp(options, names);