假设我有一个遵循以下模式的对象数组:
var posts = [
{
title: post_ab,
category_array : [
{ id: 1, slug: category-a },
{ id: 2, slug: category-b }
]
},
{
title: post_ac,
category_array : [
{ id: 1, slug: category-a },
{ id: 3, slug: category-c }
]
},
{
title: post_bc,
category_array : [
{ id: 2, slug: category-b },
{ id: 3, slug: category-c }
]
}
]
我正在尝试过滤上述数组,并且仅返回category_array 包含与指定值匹配的 slug 的值。
例如,如果我想过滤“category-c”,则只会返回第二个和第三个值(post_ac 和 post_bc)。
我尝试过使用嵌套过滤器,但没有任何结果:
var currentCategory = 'category-b';
var filteredPosts = function( posts ) {
return posts.filter( function( post ){
return post.category_array.filter( function( category ){
return category.slug === currentCategory;
})
})
}
最佳答案
您必须使用Array.prototype.some()在内循环中:
var filteredPosts = function(posts) {
return posts.filter(function(post){
return post["category_array"].some(function(category){
return category.slug === currentCategory;
});
});
}
它将返回一个可在 .filter()
回调中使用的 boolean
结果。
关于javascript - 如何根据数组的嵌套数组之一的值来过滤数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43631697/