最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get nested JSONobject value without needing many intermediate checks? - Stack Overflow

programmeradmin3浏览0评论

suppose i have a plex json object x with mixed objects and arrays. Is there a simple or generic way to check if a variable is null or undefined within this object, such as:

if(x.a.b[0].c.d[2].e!=null) ....

instead of normally checking all the parent fields

if(x.a!=null 
&& x.a.b!=null
&& x.a.b[0]!=null
&& x.a.b[0].c!=null
&& x.a.b[0].c.d!=null
&& x.a.b[0].c.d[2]!=null
&& x.a.b[0].c.d[2].e!=null) ....

suppose i have a plex json object x with mixed objects and arrays. Is there a simple or generic way to check if a variable is null or undefined within this object, such as:

if(x.a.b[0].c.d[2].e!=null) ....

instead of normally checking all the parent fields

if(x.a!=null 
&& x.a.b!=null
&& x.a.b[0]!=null
&& x.a.b[0].c!=null
&& x.a.b[0].c.d!=null
&& x.a.b[0].c.d[2]!=null
&& x.a.b[0].c.d[2].e!=null) ....
Share Improve this question edited Jan 2, 2013 at 4:58 user166390 asked Jan 2, 2013 at 4:47 konghoukonghou 5577 silver badges20 bronze badges 2
  • (Checking for if the last value is undefined/null is just a subset of the entire task.) – user166390 Commented Jan 2, 2013 at 4:50
  • I don't see any JSON in this question... – James Sumners Commented Jan 2, 2013 at 5:14
Add a ment  | 

2 Answers 2

Reset to default 6
try {
   if(x.a.b[0].c.d[2].e!=null)
    //....
} catch (e) {
    // What you want 
}

Live DEMO

Here is a variant that doesn't require exception handling .. will it be faster? I doubt it. Will it be cleaner? Well, that depends upon personal preference .. of course this is just a small demonstrative prototype and I am sure there are better "JSON query" libraries already in existence.

// 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); 
}
发布评论

评论列表(0)

  1. 暂无评论