I don't recommend iterating through the entire object using custom methods, but if you really can't access the object directly, you can use a recursive function and pass the keys you want to open. This might give you a bit more of the dynamic feeling you want.
Code:
function readObjectValue(obj, key, defaultValue) {
function __readObjectValueInternal(obj, keyParts, defaultValue) {
if (!obj.hasOwnProperty(keyParts[0])) {
return defaultValue;
}
var readValue = obj[keyParts[0]];
if (typeof(readValue) !== 'object') {
return readValue;
}
return __readObjectValueInternal(readValue, keyParts.slice(1), defaultValue);
};
return __readObjectValueInternal(
obj,
(typeof(key) === 'string' ? key.split(/\./g) : key),
defaultValue
);
}
Usage:
var json = {
abc: 1,
def: 2,
ghi: [3, 4]
};
console.log( readObjectValue(json, 'abc') ); // 1
console.log( readObjectValue(json, 'ghi.1') ); // 4
console.log( readObjectValue(json, 'ghi.2') ); // undefined
console.log( readObjectValue(json, 'ghi.3', null) ); // null
console.log( readObjectValue(json, ['def', 0], null) ); // 2