使用2个JSON过滤结果

filter result using 2 JSON

本文关键字:结果 过滤 JSON 2个 使用      更新时间:2023-09-26

这是我保存的本地存储,

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

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

{
    "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",
                }
            ]
        }
    ]
}

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

我更喜欢使用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>

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

如果你想要"HP",你就想要行业2,而不是行业1。

CCD_ 4并不是真正的最优。您可以使用.find(...),但这还没有得到普遍支持。或者,您可以使用普通的旧JavaScript并编写for循环,以使其快速运行。或者,您可以使用带有ID键的对象而不是数组来加快查找速度。

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

假设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);

从上面的片段中,任何符合搜索条件的商家都将被带到匹配列表中。它对你来说可读性更强吗?

您甚至需要数字id吗?当你不这样做的时候会变得非常容易。

/*
{
    "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);