Please help on how to use variable in Grep filter..
the return n.state_id == 1 || n.state_id == 3;
works but if it’s inside a variable it’s not working.
var json_data = [{"id":147,"state_id":1,"value":1}, {"id":147,"state_id":1,"value":4},{"id":147,"state_id":2,"value":1}, {"id":147,"state_id":3,"value":1}];
$filter_state = ['1','3'];
var state_filter = '';
for (let key in $filter_state){
var operator_key = key==0 ? '' : ' || ';
state_filter+= operator_key + 'n.state_id == ' + $filter_state[key] + '';
}
jQuery('#state_filter').html(state_filter);
// This one works
var filter_1 = $.grep( json_data, function( n, i) {
return n.state_id == 1 || n.state_id == 3;
});
console.log(filter_1);
// This is one is not
var filter_2 = $.grep( json_data, function( n, i) {
return state_filter;
});
console.log(filter_2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
State Filter: <div id="state_filter"></div>
2
Answers
There is ZERO need for jQuery here
NOTE I changed the states to ints. If you want to keep them strings, you will need to cast the state_id to string too
If you MUST use $.grep, then you can use the same test
If you want to define the item to test beforehand, do so
according to documentation :
so in
filter_1
the result of expression istrue
orfalse
but in
filter_2
the State Filter is a string and a string is alwaystrue
(empty string is false).therefore in filter_2 all items will be passed.