Here is an option that does not require exception handling .. will it be faster? I doubt it. Will it be cleaner? Well, it depends on personal preference. Of course, this is just a small demo prototype, and I'm sure that existing JSON request libraries already exist.
// returns the parent object for the given property // or undefined if there is no such object function resolveParent (obj, path) { var parts = path.split(/[.]/g); var parent; for (var i = 0; i < parts.length && obj; i++) { var p = parts[i]; if (p in obj) { parent = obj; obj = obj[p]; } else { return undefined; } } return parent; } // omit initial parent/object in path, but include property // and changing from [] to . var o = resolveParent(x, "ab0.cd2.e"); if (o) { // note duplication of property as above method finds the // parent, should it exist, so still access the property // as normal alert(oe); }
user166390
source share