'how can i change array of object to object of array in javascript?

I am trying to convert array of objects to object of array using javascript.

Here is the code

const data = [
{
  items: [
    {
      code: "location_list_page",
      icon: "environment",
      id: 1,
      link: "/configurations/locations",
      name: "Localisations",
    }
  ]
},
{
  items: [
    {
      code: "service_list_page",
      icon: "api",
      id: 5,
      link: "/configurations/services",
      name: "Services",
    }
  ]
 }
]

I want to create this object:

const data = {
  items: [
    {
      code: "location_list_page",
      icon: "environment",
      id: 1,
      link: "/configurations/locations",
      name: "Localisations",
    },
    {
      code: "service_list_page",
      icon: "api",
      id: 5,
      link: "/configurations/services",
      name: "Services",
    }
  ]
}

I try to solve it using map in array method but it didn't work.

Anyone can help me please ???



Solution 1:[1]

This is a pretty straightforward use of flatMap:

const data = [
{
  items: [
    {
      code: "location_list_page",
      icon: "environment",
      id: 1,
      link: "/configurations/locations",
      name: "Localisations",
    }
  ]
},
{
  items: [
    {
      code: "service_list_page",
      icon: "api",
      id: 5,
      link: "/configurations/services",
      name: "Services",
    }
  ]
 }
]

const result = {items: data.flatMap(x => x.items)};

console.log(result);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jamiec