javascript - Filtering array of objects with multiple attribute on multiple condition -
i trying filter array of objects multiple attribute on multiple condition. i'm creating param array consists of of multiple array holding parameters. example
var params = [ ["id", "equals", "11060"], ["user_id", "exact", "84"] ];
first element key , second 1 condition , third 1 value. first filtering condition id == '11060'
, second 1 user_id = '84'
// data filter var originaldata = [{ "id": 11141, "user_id": 84, "received": "26 jan 2017", "approvalstatus": "approved" }, { "id": 11080, "user_id": 84, "received": "25 jan 2017", "approvalstatus": "approved" }, { "id": 11079, "user_id": 84, "received": "25 jan 2017", "approvalstatus": "approved" }, { "id": 11078, "user_id": 84, "received": "25 jan 2017", "approvalstatus": "approved" }, { "id": 11060, "user_id": 84, "received": "24 jan 2017", "approvalstatus": "approved" }];
following filtering function.
filtereddata = originaldata.filter(function(item) { params.foreach(function(value, index) { var cond = value[1]; var ckey = value[0]; var cvalue = value[2]; var flag = false; if (cond == 'equals') { if (item[ckey] == number(cvalue)) { flag = true; } } else if (cond == 'exact'){ if (item[ckey].tostring() == cvalue) { flag = true; } } return flag; }); return false; });
but it's not working. doing wrong? tia.
you foreach(), return value not transmitted return value of filtering function. also, didn't decided if value must pass test or one. assume it's test must passed successfully. if it's 1 of them, code different.
filtereddata = originaldata.filter(function(item) { var i, ntest, ckey, cvalue, flag; for(i=0, ntest=params.length; i<ntest; ++i) { ckey = params[i][0]; cvalue = params[i][2]; switch(params[i][1]) { case "equals": if(item[ckey] != number(cvalue)) return false; break; case "exact": if(item[ckey].tostring() != cvalue) return false; break; } } return true; });
Comments
Post a Comment