Skip to content Skip to sidebar Skip to footer

In Javascript, Test For Property Deeply Nested In Object Graph?

I've got a collection of disparate, complex JSON objects from a CouchDB database. Each contains many levels of nested properties--for example, tps_report.personnel_info.productivi

Solution 1:

functionisset(obj, propStr) {
    var parts = propStr.split(".");
    var cur = obj;
    for (var i=0; i<parts.length; i++) {
        if (!cur[parts[i]])
            returnfalse;
        cur = cur[parts[i]];
    }
    returntrue;
}

Note that the second parameter is a string, so the exception doesn't get thrown when accessing a property on a nonexistent property.

Solution 2:

Theres a function defined on this blog to safely read nested properties from a JS object

It allows you to mine an object for properties... ie.

safeRead(tps_report, 'personnel_info', 'productivity', 'units_sold');

and if any part of the object chain is null or undefined it returns an empty string....

Solution 3:

/**
 * units sold from each TPS report
 */var units;

// the hard way
units = (report && report.personnel && report.personnel.info &&
        report.personnel.info.sales && report.personnel.info.sales.units &&
        report.personnel.info.sales.units.sold) || 0;

// the easy way
units = selectn('personnel.info.sales.units.sold', report) || 0;

// resulting actionif (units < 10) fireEmployee();

Shameless plug: I am the author of selectn. It is avaialble via npm install selectn or bower install selectn or component install wilmoore/selectn.

Check out the examples on the readme to find out why this is better than an isset clone. You can also use it as a filter predicate so you can scrub out nested objects that do not contain a particular deeply nested property.

Solution 4:

You can use my ObjectPath to query big nested JSON documents. The cause I'm building it is the lack of good tools in programming languages to work with JSON just as mentioned in the question.

The project is open sourced and under AGPL license.

http://adriank.github.io/ObjectPath/

Javascript implementation is not optimized and lacks half of the Python's functionality but I'm keen to add new things if needed by community - just ping me about what is crucial to you.

Solution 5:

I really like the elegance of jsonpath, an equivalent to xpath, but for json.

http://goessner.net/articles/JsonPath/

There you can do an expression like:

var units_sold = jsonPath(tpsResports, '$.[*].personnel_info.productivity.units_sold');
// units_sold is array of found values... 

(I didn't double check my expression, it may be wrong for what you want in your example)

Post a Comment for "In Javascript, Test For Property Deeply Nested In Object Graph?"