Getting a nested JSON / object value without the need for a lot of intermediate checks?

suppose I have a complex json object x with mixed objects and arrays. Is there a simple or general way to check if a variable is null or undefined inside this object, for example:

if(xab[0].cd[2].e!=null) .... 

instead of just checking all parent fields

 if(xa!=null && xab!=null && xab[0]!=null && xab[0].c!=null && xab[0].cd!=null && xab[0].cd[2]!=null && xab[0].cd[2].e!=null) .... 
+6
source share
2 answers
 try { if(xab[0].cd[2].e!=null) //.... } catch (e) { // What you want } 

Live demo

+6
source

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); } 
+3
source

All Articles