【问题标题】:Merge values in array from multidimensional array从多维数组合并数组中的值
【发布时间】:2021-11-26 10:20:15
【问题描述】:

我是一个 JS 初学者,我被数组/对象项所困扰。 我得到一个带有 fetch 请求的 JSON 文件,我想提取部分数据。

我的数据如下所示:

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

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

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

我该怎么做?

【问题讨论】:

    标签: javascript arrays object multidimensional-array foreach


    【解决方案1】:

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

    【讨论】:

    • 通过 Set 运行它,因为标签可以有重复
    • 非常感谢。我添加了 forEach(+if) 条件来排除重复,一切都很好。
    猜你喜欢
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    相关资源
    最近更新 更多