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
and filters
. Is a for 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!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…