skip to Main Content

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


  1. 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

    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}];
    
    const filter_states = [1, 3];
    const filter_2 = json_data.filter(({state_id}) => filter_states.includes(state_id))
    console.log(filter_2);

    If you MUST use $.grep, then you can use the same test

    const filter_states = [1, 3];
    const filter_2 = $.grep( json_data, function( n, i) {
      return filter_states.includes(n.state_id)
    });
    

    If you want to define the item to test beforehand, do so

    const filterArr = [1, 3];
    const item = "state_id";
    const filter_2 = $.grep( json_data, function( n, i) {
      return filterArr.includes(n[item])
    });
    
    Login or Signup to reply.
  2. according to documentation :

    The $.grep() method removes items from an array as necessary so that
    all remaining items pass a provided test. The test is a function that
    is passed an array item and the index of the item within the array.
    Only if the test returns true will the item be in the result array.

    so in filter_1 the result of expression is true or false
    but in filter_2 the State Filter is a string and a string is always true (empty string is false).

    therefore in filter_2 all items will be passed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search