Javascript 将返回没有特定字符串的对象数组的ES6.filter()
我能够根据数组是否包含等于的标记成功返回数组。代码如下:Javascript 将返回没有特定字符串的对象数组的ES6.filter(),javascript,arrays,ecmascript-6,Javascript,Arrays,Ecmascript 6,我能够根据数组是否包含等于的标记成功返回数组。代码如下: getFeatured() { return blogPosts.filter((item) => ( item.tags.some((value) => value === 'Featured') )) } 这会过滤每个博客文章,然后我在文章中的标记数组中使用.some() 我现在需要创建一个函数,返回不包含单词“Featured”的帖子数组 以下是迄今为止的功能: renderR
getFeatured() {
return blogPosts.filter((item) => (
item.tags.some((value) => value === 'Featured')
))
}
这会过滤每个博客文章,然后我在文章中的标记数组中使用.some()
我现在需要创建一个函数,返回不包含单词“Featured”的帖子数组
以下是迄今为止的功能:
renderRegular() {
const regularPost = blogPosts.filter((item) => (
item.tags.find((value) => value !== 'Featured' )
))
console.log(regularPost)
}
find
将返回与您的条件匹配的第一个元素,因为它将返回一个元素,即一个将始终计算为true的字符串。使用indexOf
搜索是否存在字符串
renderRegular() {
const regularPost = blogPosts.filter((item) => (
item.tags.indexOf('Featured') === -1
))
console.log(regularPost)
}
您需要使用而不是,如果所有元素都满足谓词,它将返回true
。在这种情况下,如果所有标签(每个标签)不等于“特色”
,或者换一种方式,如果没有一个标签等于“特色”
(另请参见@Barmar的答案):
const posts=[{
标题:"邮政1",,
标签:[“特色”],
}, {
标题:"邮政2",,
标签:['Foo','Featured'],
}, {
标题:"邮政3",,
标签:['Bar'],
}];
const regularPost=posts.filter(项=>
item.tags.every(value=>value!=='Featured');
控制台日志(regularPost)代码>简单地否定测试不是这样做的方法。如果标签是Tag1,Featured,Tag2
,您的测试将成功,因为“Tag1”!=“特色”
相反,您需要否定some()
的结果,而不是其中的测试
renderRegular() {
return blogPosts.filter((item) => (
!item.tags.some((value) => value === 'Featured')
))
}
或者你可以申请。“some X==Y”的对立面是“every X!=Y”:
您可以分配项目:
renderRegular() {
const regularPost = blogPosts.filter((item) =>
// assign item so the filter will return item matched condition with the find
item = item.tags.find((value) => value !== 'Featured'
))
}
好的,问题是什么?我同意使用一些方法的解决方案,但我仍然怀疑使用每种方法。也许,我觉得很奇怪。试着在纸上执行它,你会发现它是正确的。如果数组中的每个元素都不等于特色
,这意味着数组中不包含特色
。那么将不会列出帖子。。。我的想法就是这样的。它应该列出除特色标签以外的所有其他帖子。这就是它将要做的every()
不是在文章数组上操作,而是在标签数组上一次只操作一篇文章。如果标记数组不包含特征
,every()
返回true
,那么filter
返回该帖子。查看Danziger答案中的代码片段,它们表明它是有效的。
renderRegular() {
const regularPost = blogPosts.filter((item) =>
// assign item so the filter will return item matched condition with the find
item = item.tags.find((value) => value !== 'Featured'
))
}