suppose i have a complex 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) ....
Accessing nested json objects is just like accessing nested arrays. Nested objects are the objects that are inside an another object. In the following example 'vehicles' is a object which is inside a main object called 'person'. Using dot notation the nested objects' property(car) is accessed.
Flatten a JSON object: var flatten = (function (isArray, wrapped) { return function (table) { return reduce("", {}, table); }; function reduce(path, accumulator, table) { if (isArray(table)) { var length = table.
Objects can be nested inside other objects. Each nested object must have a unique access path. The same field name can occur in nested objects in the same document.
try {
if(x.a.b[0].c.d[2].e!=null)
//....
} catch (e) {
// What you want
}
Live DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With