Filter a number of javascript objects using an arr

2019-01-29 04:03发布

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

[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"…}

When finished the object with category_id 19012000 should be the only one left.

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

I've made a number of attempts with different versions of iteratee functions with filter, map and each and tried key value filters with keys, values, invert, pick and omit. After trying this, which I believe should work I reach out to you:

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

where goodDates is the list of objects and category_id is the array above.

2条回答
劫难
2楼-- · 2019-01-29 04:25

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))
查看更多
混吃等死
3楼-- · 2019-01-29 04:47

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);
});
查看更多
登录 后发表回答