简体   繁体   中英

How to filter a JSON tree according to an attribute inside

I have to re-post this questions with more details again:

I got a JSON tree array .

The structure of JSON tree looks like this:

{
"app": {

    "categories": {

        "cat_222": {
            "id": "555",
            "deals": [{
                "id": "73",
                "retailer": "JeansWest"

            }, {
                "id": "8630",
                "retailer": "Adidas"

            }, {
                "id": "11912",
                "retailer": "Adidas"

            }]
        },

        "cat_342": {
            "id": "232",
            "deals": [{
                "id": "5698",
                "retailer": "KFC"
            }, {
                "id": "5701",
                "retailer": "KFC"
            }, {
                "id": "5699",
                "retailer": "MC"

            }]
        }
    }
  }
}

now, I'd like to filter this JSON tree with var pattern="KF" ,

return all with retailer name contains KF with it's id.

======================update===========================

Just check my other question. It got solved. filter multi-dimension JSON arrays

Well, you can use _.filter :

var filteredArray = _.filter(arrayOfStrings, function(str) { 
  return str.indexOf(data) !== -1; });

... or jQuery.grep :

var filteredArray = $.grep(arrayOfStrings, function(str) { 
  return str.indexOf(data) !== -1; });

As you see, the approaches are quite similar - and, in fact, both use Array.filter , if it's available in the host environment.

Also note that the original array is not affected here. If you want otherwise, just assign the result of filtering to the same variable (ie, arrayOfStrings in this example).

如果需要支持IE <9,请使用Array.filter_.filter

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