【问题标题】:Create an array from nested array of objects in vue [closed]从vue中的嵌套对象数组创建一个数组[关闭]
【发布时间】:2021-07-12 23:16:30
【问题描述】:

我有一个对象如下:

{
  "stage": [
    {
      "name": "Stage 1",
      "rounds": [
        {
          "matches": [
            {
              "id": 1,
              "start_at": "2021-04-01"
            },
          ]
        },
        {
          "matches": [
            {
              "id": 3,
              "start_at": "2021-04-03"
            }
          ]
        }
      ]
    },
    {
      "name": "Stage 2",
      "rounds": [
        {
          "matches": [
            {
              "id": 7,
              "start_at": "2021-04-07"
            }
          ]
        },
        {
          "matches": [
            {
              "id": 8,
              "start_at": "2021-04-08"
            }
          ]
        }
      ]
    }
  ]
}

我需要将所有带有酱键的值放入一个单独的数组中,以便我可以创建一个菜单。 我需要一个单独的数组中的所有“start_at”值,例如:

[
  "2021-04-01",
  "2021-04-03",
  "2021-04-04",
]

在 vue.js 中,我可以单独访问“start_at”值,但我希望将它们全部放在一起

【问题讨论】:

    标签: javascript arrays vue.js object vuejs2


    【解决方案1】:

    您可以使用flatMap 来实现此目的。

    const obj = {
      stage: [
        {
          name: "Stage 1",
          rounds: [
            {
              matches: [
                {
                  id: 1,
                  start_at: "2021-04-01",
                },
              ],
            },
            {
              matches: [
                {
                  id: 3,
                  start_at: "2021-04-03",
                },
              ],
            },
          ],
        },
        {
          name: "Stage 2",
          rounds: [
            {
              matches: [
                {
                  id: 7,
                  start_at: "2021-04-07",
                },
              ],
            },
            {
              matches: [
                {
                  id: 8,
                  start_at: "2021-04-08",
                },
              ],
            },
          ],
        },
      ],
    };
    
    const result = obj.stage.flatMap(({ rounds }) => {
      return rounds.flatMap(({ matches }) => matches.flatMap((m) => m.start_at));
    });
    
    console.log(result);

    【讨论】:

      猜你喜欢
      • 2019-09-23
      • 2020-12-21
      • 1970-01-01
      • 2021-11-28
      • 2022-01-18
      • 2018-08-20
      • 2022-11-25
      • 1970-01-01
      • 2019-10-06
      相关资源
      最近更新 更多