Home > Mobile >  Hierarchy grouping on JSON object using reduce
Hierarchy grouping on JSON object using reduce

Time:11-26

Currently I have an array of object which needs to be converted into hierarchy based on there key values. I am using reduce to achieve this , I was able to group on the 1st level of key (AREA) but I want it to happen recursively for other fields too and end result should be an hierarchy which looks like bellow , my hierarchy is huge but for example here I am taking 3 levels

Bellow is my array of object JSON

[{
    "AREA": "EMEA",
    "SUPER_REGION": "West Mediterranean Region",
    "STATE": "Portugal",
},
{
    "AREA": "USAC",
    "SUPER_REGION": "United States",
    "STATE": "california",

},
{
    "AREA": "USAC",
    "SUPER_REGION": "United States",
    "STATE": "Texas",

},
{
    "AREA": "ASIA",
    "SUPER_REGION": "Japan",
    "STATE": "Japan",

},
{
    "AREA": "EMEA",
    "SUPER_REGION": "North Europe Region",
    "STATE": "ECOE",

},
{
    "AREA": "USAC",
    "SUPER_REGION": "United States",
    "STATE": "Georgia",

}]

Expected result

[{
    "EMEA": {
        "West Mediterranean Region": {
            "Portugal": null
        },
        "North Europe Region": {
            "ECOE": null
        }
    }
},
{
    "USAC": {
        "United States": {
            "Georgia": null
        },
        "United States": {
            "Texas": null
        },
        "United States": {
            "california": null
        }
    }
},
{
    "ASIA": {
        "Japan": {
            "Japan": null
        }
    }
}]

code I have tried so far :

const result = data.reduce((grouped_Data, hierarchy) => {
    const region = hierarchy["AREA"];
    if (grouped_Data[region] == null) grouped_Data[region] = [];
    grouped_Data[region].push(hierarchy);
    return grouped_Data;
}, {});

CodePudding user response:

You could reduce with each AREA as the key in the accumulator and group at each level

const input = [{AREA:"EMEA",SUPER_REGION:"West Mediterranean Region",STATE:"Portugal"},{AREA:"USAC",SUPER_REGION:"United States",STATE:"california"},{AREA:"USAC",SUPER_REGION:"United States",STATE:"Texas"},{AREA:"ASIA",SUPER_REGION:"Japan",STATE:"Japan"},{AREA:"EMEA",SUPER_REGION:"North Europe Region",STATE:"ECOE"},{AREA:"USAC",SUPER_REGION:"United States",STATE:"Georgia"}];

const grouped = input.reduce((acc, { AREA, SUPER_REGION, STATE }) => {
  acc[AREA] ??= { [AREA]: {} }
  acc[AREA][AREA][SUPER_REGION] ??= { }
  acc[AREA][AREA][SUPER_REGION][STATE] = null
  return acc;
}, {})

console.log(
  Object.values(grouped)
)

  • Related