简体   繁体   English

如何根据内部属性过滤JSON树

[英]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 . 我有一个JSON树array

The structure of JSON tree looks like this: JSON树的结构如下所示:

{
"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" , 现在,我想用var pattern="KF"过滤这个JSON树,

return all with retailer name contains KF with it's id. 使用retailer名称返回all包含带有ID的KF

======================update=========================== ======================更新===========================

Just check my other question. 请检查我的其他问题。 It got solved. 它解决了。 filter multi-dimension JSON arrays 过滤多维JSON数组

Well, you can use _.filter : 好吧,你可以使用_.filter

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

... or jQuery.grep : ...或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. 如您所见,这些方法非常相似 - 事实上,如果它在主机环境中可用,则都使用Array.filter

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). 如果您不想要,只需将过滤结果分配给同一个变量(即本例中的arrayOfStrings )。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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