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;
})
})
}
post.category_array.someand it should work fine.