Trying to apply a filter to a nested array full of objects
Solution 1
You can use filter
on resources
. Inside the filter, since you already know that an object has categories, you can just use some
to check if the category name you are looking for is included
const resources = [{
title: 'Learn JS',
categories: [{
name: 'javascript'
}, {
name: 'css'
}]
}, {
title: 'Learn CSS',
categories: [{
name: 'css'
}]
}, {
title: 'Learn other stuff',
categories: [{
name: 'jQuery'
}, {
name: 'javascript'
}]
}, {
title: 'Learn node',
categories: [{
name: 'node'
}]
}, {
title: 'Learn React',
categories: [{
name: 'react'
}]
}];
function filterViaCategory(arr, category) {
return arr.filter(obj => obj.categories.some(cat => cat.name === category));
}
console.log(filterViaCategory(resources, 'javascript'));
Solution 2
You can try using filter
and some
array methods:
function getResourcesByCategoryName(Resources, CategoryName){
return Resources.filter(function(resource){
return resource
.categories
.some(function(category){ return category.name == CategoryName; });
});
}
Comments
-
fresh5447 almost 2 years
I have a resources array which is full of objects. Each object has categories array full of objects. I am trying to apply a filter to only return resources that have category objects of a specific name. I am having some trouble with the nesting of my data object.
Here is the data I am working with:
const resources = [ { title: 'Learn JS', categories: [ { name: 'javascript' }, { name: 'css' } ] }, { title: 'Learn CSS', categories: [ { name: 'css' } ] }, { title: 'Learn other stuff', categories: [ { name: 'jQuery' }, { name: 'javascript' } ] }, { title: 'Learn node', categories: [ { name: 'node' } ] }, { title: 'Learn React', categories: [ { name: 'react' } ] }, ];
Here are my two attempts. Both return empty arrays. Am I wrong to be trying to use
maps
andfilters
. Is afor loop
necessary?//GOAL: Return only the resources that have a category with name 'javascript' const attemptOne = resources.filter((item) => { return item.categories.forEach((thing, index) => { return thing[index] === 'javascript' }); }).map((item) => { return item; }) const attemptTwo = resources.filter((item) => { item.categories.filter((ci) => { return ci.name === 'javascript' }).map((nextItem) => { return nextItem; }); })
I have been stumbling around with this for a while, and I am not sure if I am just over complicating it our what. Thanks in advance!