我有一个充满对象的资源数组。每个对象都有充满对象的类别数组。我正在尝试应用过滤器以仅返回具有特定名称的类别对象的资源。我在嵌套数据对象时遇到了一些问题。
这是我正在处理的数据:
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'
}
]
},
];
这是我的两次尝试。两者都返回空数组。我尝试使用 maps
和 filters
是不是错了。是否需要 for 循环
?
//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;
});
})
我已经在这个问题上摸索了一段时间,我不确定我是否只是把它复杂化了。提前致谢!
最佳答案
您可以对资源
使用过滤器
。在过滤器内部,因为您已经知道一个对象有类别,所以您可以只使用 some
检查是否包含您要查找的类别名称
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'));
关于javascript - 尝试将过滤器应用于充满对象的嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38517373/