gpt4 book ai didi

javascript - 如何使用Javascript从对象数组内的数组属性中获取不同的值

转载 作者:行者123 更新时间:2023-12-04 07:47:58 29 4
gpt4 key购买 nike

所以说我有一个这样的数据集。

posts = [
{
title: 'title1',
category: 'cat1',
tags: ['tag1', 'tag2', 'tag3', 'tag4']
},
{
title: 'title2',
category: 'cat1',
tags: ['tag1', 'tag2', 'tag5']
}];
我想获得所有帖子中唯一标签的列表,如下所示:
['tag1', 'tag2', 'tag3', 'tag4', 'tag5']
我找到了 this response这涵盖了如何针对单个 Prop 进行此操作:
const categories = [...new Set(posts.map(post => post.category))];
但我似乎无法获得标签的语法。像这样(可预测),添加数组而不是破坏的值:
const tags = [...new Set(posts.map(post => post.tags))];
显然我可以遍历每个帖子并以这种方式抓取它们,但我确信有一种更优雅的使用 ES6 的方式,我只是还没有想出。这里有什么想法吗?

最佳答案

使用 Array.flatMap()得到一个扁平的标签数组来创建集合:

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);

Array.flatMap()不支持,您可以传播您创建的数组数组 Array.map()进入 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);

关于javascript - 如何使用Javascript从对象数组内的数组属性中获取不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67118580/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com