因此,我有如下数据:
[
{
"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) })发布于 2018-07-02 02:19:53
您不希望在filter中使用filter --相反,在过滤器中,检查tags对象的some是否具有所需的.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)
)));
发布于 2018-07-02 02:26:25
要使用filter(),您需要返回真或假的东西--即布尔值。那应该是你第一个开始的地方。所以给出这样的对象
{
"id": 0,
"title": "happy dayys",
"owner": {"id": "1", "username": "dillonraphael"},
"tags": [{"value": "Art", "label": "Art"}],
"items": []
},如果您想决定是否应该使用它,可以在tags数组上尝试使用tags。这将返回一个布尔值。
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') ))
https://stackoverflow.com/questions/51128388
复制相似问题