Skip to content
Advertisement

Create an array from nested array of objects in vue [closed]

I have an object as follows:

{
  "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"
            }
          ]
        }
      ]
    }
  ]
}

I need to put all the values with the sauce key into a separate array so that I can create a menu. i need all “start_at” values inside a separate array, like:

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

in vue.js i have access “start_at” values separately, but I want them all together

Advertisement

Answer

You can use flatMap to achieve this.

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);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement