我有一个对象数组,每个对象都是一个嵌套的整数数组。
[
{
"title": "Foo",
"date": "2018-02-08T15:55:16",
"author": 2,
"categories": [
229,
190
]
},
{
"title": "Bar",
"date": "2018-02-08T15:55:16",
"author": 2,
"categories": [
199,
17
]
},
{
"title": "Baz",
"date": "2018-02-08T15:55:16",
"author": 2,
"categories": [
199,
229
]
}
]
我想要做的是从给定的categoryIds数组中检索一个对象数组 - [229,17]会检索第一个两个项目吗?
尝试使用过滤器,但很难进入类别数组。
var selectedCategories = [229,17];
posts = posts.filter(function(c) {
return selectedCategories.includes(c.categories);
});
// posts output: []
答案 0 :(得分:1)
对于每个帖子,您应该查看其中任何关联类别是否具有selectedCategories
中存在的ID。 for ... of
回调中的简单posts.filter
循环应该可以解决问题:
var posts = [
{
"title": "Foo",
"date": "2018-02-08T15:55:16",
"author": 2,
"categories": [
229,
190
]
},
{
"title": "Bar",
"date": "2018-02-08T15:55:16",
"author": 2,
"categories": [
199,
17
]
},
{
"title": "Baz",
"date": "2018-02-08T15:55:16",
"author": 2,
"categories": [
199,
230 // Note: I made this 230 to exclude this item
]
}
];
var selectedCategories = [229,17];
posts = posts.filter(function(c) {
for (let categoryId of c.categories) {
if (selectedCategories.includes(categoryId)) return true;
}
return false;
});
console.log(posts);

答案 1 :(得分:1)
您非常接近,但必须针对每个选定的类别(或直到找到匹配项)检查每个类别。您可以使用.some()
。
posts = posts.filter(p =>
p.categories.some(cat => selectedCategories.includes(cat))
);
var posts = [
{
"title": "Foo",
"date": "2018-02-08T15:55:16",
"author": 2,
"categories": [
229,
190
]
},
{
"title": "Bar",
"date": "2018-02-08T15:55:16",
"author": 2,
"categories": [
199,
17
]
},
{
"title": "Baz",
"date": "2018-02-08T15:55:16",
"author": 2,
"categories": [
199,
229
]
}
]
var selectedCategories = [229,17];
posts = posts.filter(p =>
p.categories.some(cat => selectedCategories.includes(cat))
);
console.log(posts)

答案 2 :(得分:0)
您可以创建一个类来重复使用过滤器操作。
let dataArray = [ { "title": "Foo", "date": "2018-02-08T15:55:16", "author": 2, "categories": [ 229, 190 ] }, { "title": "Bar", "date": "2018-02-08T15:55:16", "author": 2, "categories": [ 199, 17 ] }, { "title": "Baz", "date": "2018-02-08T15:55:16", "author": 2, "categories": [ 199, 229 ] }];
function MyFilter(array) {
this.array = array;
this.withKey = (key) => {
this.key = key;
return this;
}
this.withComparator = (fn) => {
this.comparator = fn;
return this;
};
this.filter = () => this.array.filter(o => this.comparator(o[this.key]));
}
let categoryIds = [229, 17];
let result = new MyFilter(dataArray).withKey('categories').withComparator((catArray) => catArray.some((c) => categoryIds.some((ic) => ic == c))).filter();
console.log(result);