dfilatov / jspath

DSL that enables you to navigate and find data within your JSON documents
MIT License
553 stars 40 forks source link

Displaying results of for inner loop (or nested $.each()) #71

Closed ginestra closed 6 years ago

ginestra commented 6 years ago

Hi, I'm having problems understanding how to retrieve values that match conditions in an inner $.each() without returning the whole object.

A JSON sample:

data = {
    "supergroup": [
        {
            "year": "2018",
            "group": [
                {
                    "id": "1",
                    "name": "bbb"
                },
                {
                    "id": "2",
                    "name": "eee"
                }
            ]
        },
        {
            "year": "2017",
            "group": [
                {
                    "id": "3",
                    "name": "bbb"
                },
                {
                    "id": "4",
                    "name": "ccc"
                }
            ]
        }
    ]
}

If I want to return all name == "bbb" but also have access to the year how would I go about it?

So far I tried nested $each()s but it returns the group as an object (as it should) where at least one child matches the condition. The problem is the list will also contain the other child that doesn't.

For instance:

JSPath.apply('.supergroup{..name == "bbb"}', data);

will return all names in the groups (id 1, 2, 3, 4).

If I run the query on the group instead: JSPath.apply('..group{..name == "bbb"}', data);

I get the expected list, but if I try to access the year, I get an undefined error.

My current function to retrieve the results is built like this:

function results(myJSPathString) {
    $.each(myJSPathString, function(k, v) {
        $.each(v.group, function(subk, subv) { // My condition is met in the group rather than on the single element
            $('#results').append('<tr><td>' +
                v.year + '</td><td>' +
                subv.id + '</td><td>' +
                subv.name + '</td></tr>');
        });
    });
}
ginestra commented 6 years ago

Solved it creating a different path for the outer and the inner objects and quering them properly:

function results() {
    $.each(JSPath.apply(path, data), function(i, supergroup) {
        $.each(JSPath.apply(subpath, supergroup), function(j, group) {
            $('#results').append('<tr><td>' +
               supergroup.year + '</td><td>' +
               group.id + '</td><td>' +
               group.name + '</td></tr>'
            );
        });
    });
}