所以我有如下数据:
[
{
"id": 0,
"title": "happy dayys",
"owner": {"id": "1", "username": "dillonraphael"},
"tags": [{"value": "Art", "label": "Art"}],
"items": []
},
{
"id": 1,
"title": "happy dayys",
"owner": {"id": "1", "username": "dillonraphael"},
"tags": [{"value": "Architecture", "label": "Architecture"}],
"items": []
},
]
我正在尝试过滤一个数组,并且仅在标签数组包含另一个字符串的值==
时返回。
这是我想出的,但似乎仍然要发回整个数组:
const tagMoodboards = _moodboards.filter(mb => { return mb.tags.filter(t => t.value == name) })
答案 0 :(得分:3)
您不希望在filter
中使用filter
-而是在过滤器中,检查some
对象中的tags
是否具有.value
您想要的属性
const _moodboards = [
{
"id": 0,
"title": "happy dayys",
"owner": {"id": "1", "username": "dillonraphael"},
"tags": [{"value": "Art", "label": "Art"}],
"items": []
},
{
"id": 1,
"title": "happy dayys",
"owner": {"id": "1", "username": "dillonraphael"},
"tags": [{"value": "Architecture", "label": "Architecture"}],
"items": []
},
];
const name = 'Architecture';
console.log(_moodboards.filter(({ tags }) => (
tags.some(({ value }) => value === name)
)));
答案 1 :(得分:0)
要使用filter()
,您需要返回true或false的值(即布尔值)。那应该是您开始的第一个地方。因此,给定类似对象
{
"id": 0,
"title": "happy dayys",
"owner": {"id": "1", "username": "dillonraphael"},
"tags": [{"value": "Art", "label": "Art"}],
"items": []
},
如果您想决定是否应该使用它,可以在tags
数组上尝试Array.some()
。这将返回一个布尔值。
let tags = [{"value": "Art", "label": "Art"}]
console.log(tags.some(tag => tag.value = "Art")) // true
有了这些,您现在可以一起使用filter()
和some()
。 some()
将为数组中的每个项目返回true或false,并确定是否对其进行过滤:
let arr = [{"id": 0,"title": "happy dayys","owner": {"id": "1", "username": "dillonraphael"},"tags": [{"value": "Art", "label": "Art"}],"items": []},{"id": 1,"title": "happy dayys","owner": {"id": "1", "username": "dillonraphael"},"tags": [{"value": "Architecture", "label": "Architecture"}],"items": []},]
console.log(arr.filter(obj => obj.tags.some(o => o.value == 'Art') ))