2 回答

TA贡献1853条经验 获得超18个赞
我有以下对象:
'1': {
id: 1,
...
tags: ['cat I', 'cat II']
},
'2': {
id: 2,
tags: ['cat II', 'cat III']
}
要获得所有类别(但没有重复),我执行以下操作:
const cats = [];
this.courses.forEach(data => (data.tags) ? cats.push(data.tags) : '');
return [...new Set(cats.flat())];
它有效,但我觉得这是“超越顶部”的方式。它也运行了两次,因为它在计算属性中。
有没有更好的方法来区分和过滤类别。也许通过向商店查询?

TA贡献1811条经验 获得超5个赞
你做:
const courses = [{id: 1, tags: ['cat I', 'cat II ']}, {id: 2, tags: ['cat II', 'cat III']}, {id: 3}]
const tags = courses
.reduce((a, { tags = [] }) => [...a, ...tags], [])
.map(tag => tag.trim()) // <-- to remove extra spaces in "cat II "
const result = [...new Set(tags)]
console.log(result)
添加回答
举报