使用2 JSON过滤结果

时间:2015-06-01 03:36:51

标签: javascript jquery json

这是我保存的本地存储,

[{"industry_Id":1,"merchant_id":2}]

我想过滤下面的结果,以获得惠普。

{
    "industries": [
        {
            "id": 1,
            "name": "oil and gas",
            "merchant": [
                {
                    "id": 1,
                    "name": "ABC",
                },
                {
                    "id": 2,
                    "name": "DEF",
                },
                {
                    "id": 3,
                    "name": "GHJ",
                }
            ]
        },
        {
            "id": 2,
            "name": "IT",
            "merchant": [
                {
                    "id": 1,
                    "name": "Apple",
                },
                {
                    "id": 2,
                    "name": "HP",
                },
                {
                    "id": 3,
                    "name": "Google",
                }
            ]
        }
    ]
}

我想过使用多个$ .each,但它必须迭代几次,这是多余的。

4 个答案:

答案 0 :(得分:1)

我更喜欢使用Javascript for循环,这样一旦找到所需的元素,就可以跳过迭代每个对象。

没有jQuery (使用for

var i, j, merchant = null;
for(i = 0; i < data['industries'].length; i++){
   if(data['industries'][i]['id'] == arg[0]['industry_Id']){
      for(j = 0; j < data['industries'][i]['merchant'].length; j++){
         if(data['industries'][i]['merchant'][j]['id'] == arg[0]['merchant_id']){
             merchant = data['industries'][i]['merchant'][j];
             break;
         }
      }

      if(merchant !== null){ break; }
   }
}

使用jQuery (使用$.each

    var merchant_found = null;
    $.each(data['industries'], function(i, industry){
       if(industry['id'] == arg[0]['industry_Id']){
          $.each(industry['merchant'], function(i, merchant){
             if(merchant['id'] == arg[0]['merchant_id']){
                merchant_found = merchant;
             }

             return (!merchant_found);            
          });
       }

       return (!merchant_found);
    });

var arg = [{"industry_Id":1,"merchant_id":2}];

    var data = {
        "industries": [
            {
                "id": 1,
                "name": "oil and gas",
                "merchant": [
                    {
                        "id": 1,
                        "name": "ABC",
                    },
                    {
                        "id": 2,
                        "name": "DEF",
                    },
                    {
                        "id": 3,
                        "name": "GHJ",
                    }
                ]
            },
            {
                "id": 2,
                "name": "IT",
                "merchant": [
                    {
                        "id": 1,
                        "name": "Apple",
                    },
                    {
                        "id": 2,
                        "name": "HP",
                    },
                    {
                        "id": 3,
                        "name": "Google",
                    }
                ]
            }
        ]
    };


    var i, j, merchant = null;
    for(i = 0; i < data['industries'].length; i++){
       if(data['industries'][i]['id'] == arg[0]['industry_Id']){
          for(j = 0; j < data['industries'][i]['merchant'].length; j++){
             if(data['industries'][i]['merchant'][j]['id'] == arg[0]['merchant_id']){
                 merchant = data['industries'][i]['merchant'][j];
                 break;
             }
          }
          
          if(merchant !== null){ break; }
       }
    }
    
    console.log(merchant);
    document.writeln("<b>Without jQuery:</b><br>");
    document.writeln((merchant !== null) ? "Found " + merchant['name'] : "Not found");

    var merchant_found = null;
    $.each(data['industries'], function(i, industry){
       if(industry['id'] == arg[0]['industry_Id']){
          $.each(industry['merchant'], function(i, merchant){
             if(merchant['id'] == arg[0]['merchant_id']){
                merchant_found = merchant;
             }
            
             return (!merchant_found);            
          });
       }

       return (!merchant_found);
    });
    
    console.log(merchant_found);
    document.writeln("<br><br><b>With jQuery:</b><br>");
    document.writeln((merchant_found) ? "Found " + merchant_found['name'] : "Not found");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

答案 1 :(得分:0)

selectors.map(function(selector) {
  return data.industries.filter(function(industry) {
    return industry.id == selector.industry_Id;
  })[0].merchant.filter(function(merchant) {
    return merchant.id == selector.merchant_id;
  })[0].name;
});
// => DEF

如果您想要&#34; HP&#34;,您需要行业2,而不是行业1.

.filter(...)[0]并不是最佳选择。您可以使用.find(...),但这尚未得到普遍支持。或者您可以使用普通的旧JavaScript并编写for循环来使其快速。或者您可以使用具有ID键的对象而不是数组来更快地进行查找。

答案 2 :(得分:0)

当涉及到您正在处理的数据收集位置时,我建议您查看 underscore.js 。它不是最佳性能的最佳选择,但它确实使您的代码更具可读性并且更有意义,尤其是与循环相比时。

Say data是一个存储JSON数据的变量。 试试这个:

// Given this selector criteria
var select = [{"industry_Id":1,"merchant_id":2}];

function filterByCriteria(criteria, data){
    var match = [];
    _.each(criteria, function(crit){

        function matchIndustry(rec){ return rec.id===crit.industry_Id }
        function matchMerchant(rec){ return rec.id===crit.merchant_id }

        // Filter by industry id
        var industry = _.first(_.where(data.industry, matchIndustry));
        // Filter by merchant id
        var merchant = _.where(industry.merchant, matchMerchant);
        _.each(merchant, function addToMatchResult(m){
            match.push(m.name);
        });
    });
    return match;
}

var filteredData = filterByCriteria(select, data);

从上面的代码段中,符合搜索条件的所有商家都会被带到匹配列表中。你觉得它更具可读性吗?

答案 3 :(得分:-1)

你甚至需要数字ID吗?如果你没有,那就太容易了。

&#13;
&#13;
/*
{
    "industry": {
	"oil and gas":{
            "merchant": {
        	"ABC": {
                    "name": "ABC oil"
        	},
                "DEF": {
                    "name": "DEF gas"
                },
                "GHJ" :{
                    "name": "GHJ oil and gas"
                }
            }
	},
	"IT": {
            "merchant": {
        	"Apple" : {
                    "name": "Apple computers"
                },
                "HP": {
                    "name": "Hewlett Packard"
                },
                "Google": {
                    "name": "Google. Maw haw haw"
                }
            }
        }
    }
}
*/
var data = '{"industry": {"oil and gas":{"merchant": {"ABC": {"name": "ABC oil"},"DEF": {"name": "DEF gas"},"GHJ" :{"name": "GHJ oil and gas"}}},"IT": {"merchant": {"Apple" : {"name": "Apple computers"},"HP": {"name": "Hewlett Packard"},"Google": {"name": "Google. Maw haw haw"}}}}}';
data = JSON.parse(data);

var merchant = data.industry['IT'].merchant['HP'];

alert(merchant.name);
//console.log(merchant.name);
&#13;
&#13;
&#13;