I want need to translate a notation (e.g. ‘main:message:new’) to the referred object property (resource[main][message][new]).
var notation = 'main:message:new';
var ressource = {
message: { new: 'something' }
};
var splitKeys = function(keys, object) {
var keys, pointer;
pointer = object;
keys = keys.split(':');
for (i = 0; i < keys.length; i++) {
// here is the error
if (pointer[keys[i]] === undefined) break;
pointer = pointer[keys[i]];
}
return pointer;
};
console.log(splitKeys(notation, ressource));
As you see I got problems with the error handling. If there is a ressource notation which doesn’t match a concrete ressource I want to return nothing. Unfortunately I always get an error thrown ‘cannot read property undefined of undefined’…
The first property name, called
main, is not present in your resource object, thus your method will always return the entire object instead of the property value you are aiming at, which is{ new: 'something' }:This will return the
newobject, i.e.,{ new: 'something' }. If you want to return the property value instead, returnpointerinstead ofparent.DEMO.