[英]Filter a number of javascript objects using an array of values for one key
I want to filter the following objects by category_id using the following array of category_id values: 我想使用以下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"…}
When finished the object with category_id 19012000 should be the only one left. 完成后,类别ID为19012000的对象应该是剩下的唯一对象。
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. 我已经尝试过使用带有过滤器,映射的iteratee函数的不同版本,并尝试使用键,值,取反,选择和忽略键值过滤器。 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. 其中goodDates是对象列表,category_id是上面的数组。
indexOf()
with a string and a number 具有字符串和数字的
indexOf()
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))
I don't see any reason to use _.first
here? 我看不出有任何理由在这里使用
_.first
吗? The rest of your filter statement looks good, altough you may swap the indexOf
call for _.contains
: 其余的filter语句看起来不错,尽管您可以将
indexOf
调用_.contains
:
var postDates = _.filter(goodDates, function(n){
return _.contains(category_id, n.category_id);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.