使用过滤值数组一些JavaScript对象的一个关键 [英] Filter a number of javascript objects using an array of values for one key
问题描述
我想用CATEGORY_ID值以下数组进行过滤CATEGORY_ID以下对象:
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"…}
在完成与CATEGORY_ID 19012000对象应该是唯一一个离开。
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"…}
我做了一些与过滤器不同版本的iteratee功能的尝试,地图和每个并试图键值过滤器的钥匙,价值观,反转,挑选和省略。尝试此,我认为应该工作后,我接触到你:
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})
,其中goodDates是对象列表和CATEGORY_ID高于阵列
where goodDates is the list of objects and category_id is the array above.
推荐答案
的indexOf()
带有字符串和数字
var a = [123];
console.log(a.indexOf(123)); //true
console.log(a.indexOf("123")); //false
您code不工作,因为你在你的对象的数字数组中的比较字符串。
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)
或
category_id.indexOf(parseInt(n.category_id, 10))
这篇关于使用过滤值数组一些JavaScript对象的一个关键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!