从多维数组合并数组中的值

Merge values in array from multidimensional array

我是一个 JS 初学者,我受困于 array/objects 个项目。 我收到一个带有获取请求的 JSON 文件,我想提取部分数据。

我的数据是这样的:

{
"profil": [
 {
  "name": "",
  "id": ,
  "city": "",
  "country": "",
  "tags": ["", "", "", ""],
  "text": "",
  "price":
 },

所以它是一个对象,其中包含一个数组,该数组包含一堆包含“标签”数组的对象....

我找不到使用 forEach 循环访问标签项(没有数组索引)的方法... 我这样做的最终目的是收集存在于我的对象列表中的单个标签列表。

我该怎么做?

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

编辑:如果你需要标签是唯一的,你可以使用Set:

console.log([...new Set(tags)]);