Function to return nested values in an object
This obviously needs to be improved upon, but the idea is there:
- var obj = {
"one" : {
"two": {
"three": 3
}
}
};
var arg = ["one", "two", "three"];
nestedValue = function(obj, arg) {
var len = arg.length;
if (len) {
if (typeof arg == "string") {
return obj[arg];
}
else {
while (arg.length) {
var key = arg.shift();
if (!obj[key]) {
return undefined;
}
else if (typeof obj[key] === "object") {
return nestedValue(obj[key], get);
}
else {
return obj[key];
}
}
}
}
// not found
return undefined;
};
nestedValue(obj, arg);
If there's an easier way to do this, please clue me in : )