Say I have an array of objects that follows the pattern below:
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 }
]
}
]
I'm trying to filter the above array, and only return values where the category_array contains a slug matching a specified value.
For example, if I wanted to filter against 'category-c', only the 2nd and 3rd values (post_ac and post_bc) would be returned.
I've tried with nested filters, which is getting me nowhere:
var currentCategory = 'category-b';
var filteredPosts = function( posts ) {
return posts.filter( function( post ){
return post.category_array.filter( function( category ){
return category.slug === currentCategory;
})
})
}
You have to use Array.prototype.some() in the inner loop:
var filteredPosts = function(posts) {
return posts.filter(function(post){
return post["category_array"].some(function(category){
return category.slug === currentCategory;
});
});
}
It will return a boolean result that can be used in the .filter() callback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With