简体   繁体   中英

Filtering JSON with underscore

Given a data structure like so:

"items":
         {
         "Groups":[
            {
               "title":"group 1",
               "SubGroups":[
                  {
                     "title":"sub1",
                     "id" : "1",
                     "items":[
                        {
                           "title":"Ajax request 1",
                        },
                        {
                           "title":"Ajax request 2",
                        }
                     ]
                  },
                    {
                     "title":"sub2",
                     "id" : "2",
                     "items":[
                        {
                           "title":"Ajax request 3",
                        },
                        {
                           "title":"Ajax request 4",
                        }
                     ]
                  }
               ]
            }
         ]

How can I pull out all the items for a sub group based on the id? Ive treid using find like so:

var res1 = _.where(listing.items,{id:"2"});

but get an empty array returned

Thanks

Try targeting the subgroups array and then search for the id you want in there. That should then return the properties for that subgroup.

var obj = {
    "Groups": [{
        "title": "group 1",
        "SubGroups": [{
            "title": "sub1",
            "id": "1",
            "items": [{
                "title": "Ajax request 1",
            }, {
                "title": "Ajax request 2",
            }]
        }, {
            "title": "sub2",
            "id": "2",
            "items": [{
                "title": "Ajax request 3",
            }, {
                "title": "Ajax request 4",
            }]
        }]
    }]
}

then find values like this

_.where(obj.Groups[0].SubGroups, {
   'id': '2'
});

Just tested and this seems to work

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