-2

I have an object with two arrays of objects being returned from an API. I need to try to map this into a new array of objects so I can group the data for the Vue v-select component. CodePen Example

fields: {
      current: [
        {
          name: 'Date'
        },
        {
          name: 'Time'
        }
      ],
      previous: [
        {
          name: 'Birthday'
        },
        {
          name: 'Comments'
        }
      ]
    },

How can I map this into a new array of objects that looks like this?

grouped: [
      {
        group: "Current",
      },
      {
        name: "Date"
      },
      {
        name: "Time"
      },
      {
        group: "Previous"
      },
      {
        name: "Birthday"
      },
      {
        name: "Comments"
      },
    ]

1 Answers1

0

Use Object.entries() to get the groups, and their values, and map them using Array.flatMap(). Create the group's object, and add it to an array with the group's items.

const flattenGroups = fields =>
  Object.entries(fields)
    .flatMap(([group, items]) => [{ group }, ...items])

const fields = {"current":[{"name":"Date"},{"name":"Time"}],"previous":[{"name":"Birthday"},{"name":"Comments"}]}

const result = flattenGroups(fields)

console.log(result)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209