Home > Enterprise >  Merge items in an array including sub items
Merge items in an array including sub items

Time:12-19

I have an array that is as follows:

 [
  {
    Region: 'Sionnach',
    Area: 'Station',
    Codes: '76534675'
  },
  {
    Region: 'Cape',
    Area: 'Dreg',
    Codes: '73457347'
  },
  {
    Region: 'Cape',
    Area: 'Dreg',
    Codes: '7653737'
  },
  {
    Region: 'Stone',
    Area: 'Lights',
    Codes: '612342136'
  },
  { 
    Region: 'Stone',
    Area: 'Pram',
    Codes:'73247237'
  },
]

I want it to appear as the following:

  [
    {
      Region: "Sionnach",
      Area: {
        Station: {
          Codes: "76534675",
        },
      },
    },
    {
      Region: "Cape",
      Area: {
        Dreg: {
          Codes: "73457347",
          Codes: "7653737",
        },
      },
    },
    {
      Region: "Stone",
      Area: {
        Lights: {
          Codes: "612342136",
        },
        Pram: {
          Codes: "73247237",
        },
      },
    },
  ]
         

Can someone please let me know how I can accomplish this? I've tried numerous ways but I can't seem to figure out what I need to do, its probably really simple, been sitting here for 3 hours and I can't seem to figure out a way to do it.

CodePudding user response:

You cannot have an object with two identical keys like

{ Codes: "73457347", Codes: "7653737" }

So I would suggest saving them as an array simply because a region area seems to might have more than one code.

To achieve what you want:

  • Using Array#reduce, iterate over the array while updating a Map where the region is the key and the expected grouped region object is the value. In each iteration, get the current region record if it exists. Then, update its Area object where the current area is the key and its codes list is the value. Finally, update the Map using Map#set.
  • Using Map#values, you get in the end the grouped list of regions with their corresponding areas.

const arr =  [ { Region: 'Sionnach', Area: 'Station', Codes: '76534675' }, { Region: 'Cape', Area: 'Dreg', Codes: '73457347' }, { Region: 'Cape', Area: 'Dreg', Codes: '7653737' }, { Region: 'Stone', Area: 'Lights', Codes: '612342136' }, { Region: 'Stone', Area: 'Pram', Codes:'73247237' } ];

const res = [...
  arr.reduce((map, { Region, Area, Codes }) => {
    const regionAreas = map.get(Region)?.Area ?? {};
    regionAreas[Area] = [...(regionAreas[Area] ?? []), Codes];
    map.set(Region, { Region, Area: regionAreas });
    return map;
  }, new Map)
  .values()
];

console.log(res);

  • Related