0

I'm trying to parse this JSON file with jquery to access the "onpage" field that is set to "true". Then use the other fields in that item (desc, icon, name & url). I can get to "items" but can figure out how to get to "onpage" inside "items". Thanks

[
{
    "group": "Home",
    "url": "http://www.home.com/"
},
{
    "group": "Production",
    "items": [
        {
            "onpage": true,
            "desc": "View local trails",
            "icon": "img/trails.png",
            "name": "Trails",
            "url": "https://www.home.com/go/Trails"
        },
        {
            "onpage": false,
            "desc": "Edit local trail",
            "icon": "img/traileditor.png",
            "name": "Trail Editor",
            "url": "https://www.home.com/go/Editor/"
        }
    ]
}

]

1 Answer 1

1

Once you've parsed it, you have an array with two objects in it. The second of those objects has a property, items, which is an array of objects. The first entry in that items array has onpage equal to true. So the direct path is:

itemWithOnPageTrue = theParsedData[1].items[0];

If you needed to find it, you'd probably use a pair of loops:

var itemWithOnPageTrue;
$.each(theParsedData, function() {
    var found;
    if (this.items) {
        $.each(this.items, function() {
            if (this.onpage) {
                itemWithOnPageTrue = this;
                found = true;
                return false;
            }
        });
        if (found) {
            return false;
        }
    }
});

$.each will stop looping if you return false, which is why we do that when we find the first match. If you don't return anything or return a different value, it will keep looping.

Once you have itemWithOnPageTrue, you can access its other properties, like itemWithOnPageTrue.desc, itemWithOnPageTrue.icon, etc.

Sign up to request clarification or add additional context in comments.

2 Comments

So to access onpage he would do theParsedData[1].items[0].onpage
@AlexW: Yes, but he wanted the object it's a part of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.