[英]How to get disinct values from an array prop inside an array of objects using Javascript
So say i have a dataset like this.所以说我有一个这样的数据集。
posts = [
{
title: 'title1',
category: 'cat1',
tags: ['tag1', 'tag2', 'tag3', 'tag4']
},
{
title: 'title2',
category: 'cat1',
tags: ['tag1', 'tag2', 'tag5']
}];
I'd like to get a list of the unique tags in all the posts like so:我想获得所有帖子中唯一标签的列表,如下所示:
['tag1', 'tag2', 'tag3', 'tag4', 'tag5']
I found this response that covers how to this for a single prop:我发现这个响应涵盖了如何针对单个道具进行此操作:
const categories = [...new Set(posts.map(post => post.category))];
But I can't seem to get the syntax for tags.但我似乎无法获得标签的语法。 Something like this (predictably), adds the arrays instead of the destructed values:
像这样(可以预见),添加 arrays 而不是破坏的值:
const tags = [...new Set(posts.map(post => post.tags))];
Obviously I can loop through each post and the grab them that way, but I'm sure there's a more elegant way using ES6 that I just haven't figured out yet.显然,我可以遍历每个帖子并以这种方式抓取它们,但我确信使用 ES6 有一种更优雅的方式,我还没有想到。 Any thoughts here?
这里有什么想法吗?
Use Array.flatMap()
to get a flattened array of tags to create the Set:使用
Array.flatMap()
获取扁平化的标签数组以创建 Set:
const posts = [{"title":"title1","category":"cat1","tags":["tag1","tag2","tag3","tag4"]},{"title":"title2","category":"cat1","tags":["tag1","tag2","tag5"]}]; const result = [...new Set(posts.flatMap(p => p.tags))]; console.log(result);
If Array.flatMap()
is not supported, you can spread the array of arrays created by your Array.map()
into Array.concat()
to flatten it:如果不支持
Array.flatMap()
,您可以将Array.map()
创建的 arrays 数组传播到Array.concat()
中以展平它:
const posts = [{"title":"title1","category":"cat1","tags":["tag1","tag2","tag3","tag4"]},{"title":"title2","category":"cat1","tags":["tag1","tag2","tag5"]}]; const result = [...new Set([].concat(...posts.map(p => p.tags)))]; console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.