javascript - filter result using 2 JSON -
this saved localstorage,
[{"industry_id":1,"merchant_id":2}]
i want filter below result, hp.
{ "industries": [ { "id": 1, "name": "oil , 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", } ] } ] }
i thought of using multiple $.each have iterate few times , it's quite redundant.
i prefer using javascript for
loop, way can skip iterating on every object once required element found.
without jquery (using for
)
var i, j, merchant = null; for(i = 0; < 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; } } }
with jquery (using $.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 , 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; < 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>
Comments
Post a Comment