これは例外処理を必要としないバリアントです..それはより速くなりますか?疑わしい。きれいになりますか?まあ、それは個人的な好みに依存します..もちろん、これはほんの小さな実証的なプロトタイプであり、より良い「JSONクエリ」ライブラリがすでに存在していると確信しています。
// 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, "a.b.0.c.d.2.e");
if (o) {
// note duplication of property as above method finds the
// parent, should it exist, so still access the property
// as normal
alert(o.e);
}