Home > database >  how can i change array of object to object of array in javascript?
how can i change array of object to object of array in javascript?

Time:01-25

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 ???

CodePudding user response:

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);

CodePudding user response:

it can be solved using map function and Object.assign() and the spread operator

var new_data = {"items": data.map(x=> Object.assign({}, ...x["items"]))};
  •  Tags:  
  • Related