使用一个键的值数组过滤多个 javascript 个对象

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

我想使用以下 category_id 值数组按 category_id 筛选以下对象:

[19012000, 19012001, 19012002, 19012003, 19012004, 19012005, 19012006, 19012007, 19012008] 



Object {_account: "mjj9jp92z2fD1mLlpQYZI1gAd4q4LwTKmBNLz", _id: "rEEwENwnznCQvkm61wRziKlMRPqaYztnR4vn61", amount: 15, category: Array[2], category_id: "13005015"…}
Object {_account: "AaaraZrLqLfzRYoAPlb6ujPELWVW4dTK4eJWj", _id: "944r40rPgPU2nXqzMYolS5nyo6Eo9OuqrlDkB", amount: 50, category: Array[3], category_id: "19012000"…}
Object {_account: "AaaraZrLqLfzRYoAPlb6ujPELWVW4dTK4eJWj", _id: "rEEwENwnznCQvkm61wZ9uey62Pjy5YTqgYGDK", amount: 24, category: Array[2], category_id: "13005007"…}
Object {_account: "mjj9jp92z2fD1mLlpQYZI1gAd4q4LwTKmBNLz", _id: "rEEwENwnznCQvkm61wRziKlMRPqaYztnR4vn61", amount: 45, category: Array[2], category_id: "13005009"…}
Object {_account: "AaaraZrLqLfzRYoAPlb6ujPELWVW4dTK4eJWj", _id: "944r40rPgPU2nXqzMYolS5nyo6Eo9OuqrlDkB", amount: 105, category: Array[3], category_id: "13005009"…}

完成后,category_id 19012000 的对象应该是唯一剩下的对象。

Object {_account: "AaaraZrLqLfzRYoAPlb6ujPELWVW4dTK4eJWj", _id: "944r40rPgPU2nXqzMYolS5nyo6Eo9OuqrlDkB", amount: 50, category: Array[3], category_id: "19012000"…}

我已经对不同版本的迭代函数进行了多次尝试,包括过滤器、映射和每个,并尝试使用键、值、反转、选择和省略的键值过滤器。在尝试了这个之后,我认为这应该有效,我联系了你:

var postDate = _.filter(_.first(goodDates), function(n){return category_id.indexOf(n.category_id) !== -1})

其中 goodDates 是对象列表,category_id 是上面的数组。

我看不出有任何理由使用 _.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);
});

indexOf() 带有一个字符串和一个数字

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

您的代码无法正常工作,因为您正在将对象中的字符串与数组中的数字进行比较。

category_id.indexOf(+n.category_id)

category_id.indexOf(parseInt(n.category_id, 10))