JavaScripter
JavaScripter

Reputation: 4842

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

Upvotes: 0

Views: 3887

Answers (2)

raina77ow
raina77ow

Reputation: 106385

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 (i.e., arrayOfStrings in this example).

Upvotes: 1

Mchl
Mchl

Reputation: 62397

Use Array.filter or _.filter if you need to support IE < 9

Upvotes: 1

Related Questions