[英]Merge values in array from multidimensional array
I'm a JS beginner and I'm stuck with array/objects items.我是一个 JS 初学者,我被数组/对象项目困住了。 I get a JSON file with a fetch request and I would like to extract a part of the data.
我收到一个带有提取请求的 JSON 文件,我想提取部分数据。
My data looks like this:我的数据如下所示:
{
"profil": [
{
"name": "",
"id": ,
"city": "",
"country": "",
"tags": ["", "", "", ""],
"text": "",
"price":
},
So it's an object, which contain an array which contain a bunch of objects which contain a "tags" array....所以它是一个 object,它包含一个数组,该数组包含一堆包含“标签”数组的对象....
I don't find a way to access tags items (without array index) with forEach loops... My final purpose with this is to collect a single list of tags that exists in my object list.我找不到使用 forEach 循环访问标签项(没有数组索引)的方法...我这样做的最终目的是收集存在于我的 object 列表中的单个标签列表。
How can I do this?我怎样才能做到这一点?
Using Array#flatMap
:使用
Array#flatMap
:
const data = { "profil": [ { "tags": ["1", "2", "3", "4"] }, { "tags": ["5", "6", "7", "8"] } ] }; const tags = data.profil.flatMap(({ tags = [] }) => tags); console.log(tags);
Edit: if you need the tags to be unique, you can use Set
:编辑:如果您需要标签是唯一的,您可以使用
Set
:
console.log([...new Set(tags)]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.