简体   繁体   中英

Arrays nested in array JSON - how to access properties

Struggling with some JSON I've been provided. It's in this format:

[
[
    {
        "items": [
            {
                "id": "xxxxxxx",
                "name": "xxxxxxxxxx",
                "description": "xxxxxxxxxxx"
            },
            {
                "id": "xxxxxxx",
                "name": "xxxxxxxxxx",
                "description": "xxxxxxxxxxx"
            }
        ],
        "parentId": "xxxxxxxx",
        "title": "xxxxxxxxx",
        "type": "xxxxxxx"
    }
],
[
    {
        "items": [
            {
                "id": "xxxxxxx",
                "name": "xxxxxxxxxx",
                "description": "xxxxxxxxxxx"
            },
            {
                "id": "xxxxxxx",
                "name": "xxxxxxxxxx",
                "description": "xxxxxxxxxxx"
            }
        ],
        "parentId": "xxxxxxxx",
        "title": "xxxxxxxxx",
        "type": "xxxxxxx"
    }
]
]

So, I have an object named 'data'. If I stringify 'data' this is what I have above. Basically I have a parentId and I need to lookup that parentId in this JSON. I'm not used to this structure and I'm floundering trying to find a (relatively) simple solution. I'm used to having something like 'items' on the top level and I can drill down through that.

for(var i=0;i<data.length;i++)
{if(data[i][0].parentId=='yourParent_id')
//stuff
}

If you're open to using a library, you can do this in Underscore ,

This:

_(data).findWhere({parentId: idToLookUp});

returns the object in an array where the parentId is equal to idToLookUp

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM