我有一系列文章,这些文章通过多对多系统链接到某些标签。当我想获取所有文章时,返回的JSON如下所示:
[
{
"id": 1,
"title": "Subin",
"content": "Integer ac leo...",
"illustration": "http://dummyimage.com/1920x1080.png/ff4444/ffffff",
"lang": "fr",
"tags": [
{
"name": "project",
"description": "Praesent id massa...",
"slug": "854963934-6",
"id": 4,
},
{
"name": "Grass-roots",
"description": "Proin eu mi...",
"slug": "528521892-6",
"id": 2,
}
]
},
{
"id": 2,
"title": "Voyatouch",
"content": "Curabitur gravida nisi at nibh...",
"illustration": "http://dummyimage.com/1920x1080.png/cc0000/ffffff",
"lang": "fr",
"tags": [
{
"name": "Grass-roots",
"description": "Proin eu mi...",
"slug": "528521892-6",
"id": 2,
},
{
"name": "User-friendly",
"description": "Vestibulum quam sapien...",
"slug": "237872269-9",
"id": 1,
}
]
},
]
我想按文章的标签过滤文章。如果我单击标签,则所有带有该标签的文章都会一直显示,而其他文章消失。
通常,如果标签只是一个字符串数组,我将执行以下操作:
filter (tag) {
// This is a VueJS context
return this.articles.filter(article => article.tag === tag)
}
但是,由于它是一个对象数组,因此我尝试执行以下操作:
filter (tag) {
let self = this
return this.articles.filter(article => {
return article.tags.filter(tag => tag.name === self.selected)
})
}
但是它什么也不返回。
正确的方法是什么?
提前谢谢
答案 0 :(得分:1)
您可以使用filter()
来过滤数组。使用some()
检查文章是否具有特定标签。
var arr = [{"id":1,"title":"Subin","content":"Integer ac leo...","illustration":"http://dummyimage.com/1920x1080.png/ff4444/ffffff","lang":"fr","tags":[{"name":"project","description":"Praesent id massa...","slug":"854963934-6","id":4},{"name":"Grass-roots","description":"Proin eu mi...","slug":"528521892-6","id":2}]},{"id":2,"title":"Voyatouch","content":"Curabitur gravida nisi at nibh...","illustration":"http://dummyimage.com/1920x1080.png/cc0000/ffffff","lang":"fr","tags":[{"name":"Grass-roots","description":"Proin eu mi...","slug":"528521892-6","id":2},{"name":"User-friendly","description":"Vestibulum quam sapien...","slug":"237872269-9","id":1}]}]
var tagName = "project"; //Tag name to search
var result = arr.filter(o => o.tags.some(x => x.name === tagName));;
console.log(result);