Filter a number of javascript objects using an array of values for one key

后端 未结 2 1200
我在风中等你
我在风中等你 2020-12-21 21:24

I want to filter the following objects by category_id using the following array of category_id values:

[19012000, 19012001, 19012002, 19012003, 19012004, 190         


        
相关标签:
2条回答
  • 2020-12-21 21:54

    indexOf() with a string and a number

    var a = [123]; 
    console.log(a.indexOf(123));  //true   
    console.log(a.indexOf("123"));  //false
    

    Your code is not working because you are comparing a string in your object to the numbers in your array.

    category_id.indexOf(+n.category_id)
    

    or

    category_id.indexOf(parseInt(n.category_id, 10))
    
    0 讨论(0)
  • 2020-12-21 21:58

    I don't see any reason to use _.first here? The rest of your filter statement looks good, altough you may swap the indexOf call for _.contains:

    var postDates = _.filter(goodDates, function(n){
        return _.contains(category_id, n.category_id);
    });
    
    0 讨论(0)
提交回复
热议问题