javascript - Angular Service Subtractive Filter -
i have angular service , i'm trying return filtered data set, using javascript's array.prototype.filter()
method. i'm matching multiple input objects' key
value
pairs set of object's key
value
pairs , returning object if match.
here service:
app.service('scatterservice', function(inputservice) { return function(data) { var inputs = inputservice.selectedinmodel(); // returns 1 - 4 user input objects function getselected(inputs) { return data.filter(function(obj) { // each user input exists angular.foreach(inputs, function(val, id) { var dataprop = val['indata']; // if prop value in data = prop value in user input if (obj[dataprop] == val['value']) { // returns objects have *either* of user inputs return true; } return false; }); }); } var newdata = getselected(inputs); console.log(newdata); }; });
this returns set of objects contain properties either value
"a" or value
"b", 1 of two. want return objects have both , b values. if there 4 theoretical user inputs, each input selected user shrinks data more , more. or, return items have of input values.
i want able functionally filter 4 potential inputs.
edit: adding object structure
inputs: { 'entertainment': { id: 'entertainment', indata: 'ent', value: '', }, 'tv': { id: 'tv', indata: 'tv', value: '17' }, 'radio': { id: 'radio', indata: 'radio', value: 'jackfm' } },
data: 300+ items
data = [ { id: '12345', ent: 30, tv: 33 }, { id: 'tv', tv: 17, ent: 999 } // ... , on ]
focusing on array.prototype.filter
section:
return data.filter(function(obj) { // each user input exists angular.foreach(inputs, function(val, id) { var dataprop = val['indata']; // if prop value in data = prop value in user input if (obj[dataprop] == val['value']) { // returns objects have *either* of user inputs return true; } return false; }); });
you returning true
when find matching property value - causes obj
selected filter when any one of values match.
instead, build result using boolean and operator on each of inputs. result true
if , if each of intermediate input tests true
. if 1 failed, result false
.
return data.filter(function(obj) { // result tracks if matching obj // assume var result = true; // each user input exists angular.foreach(inputs, function(val, id) { var dataprop = val['indata']; // , current result value input's test result = result && obj[dataprop] === val['value']; }); // return resulting chain of ands return result; });
Comments
Post a Comment