How to iterate through elements of an array in JavaScript?

Viewed 34

I am trying to group the array of objects based on the field hierarchy and my implementation is as follows, I have the array as follows,

[
  {
    "label": "AG1",
    "hierarchy": "SUPER1"
  },
  {
     "label": "AG2",
     "hierarchy": "SUPER1"
  },
  {
     "label": "MG1",
     "hierarchy": "SUPER2"
  },
  {
     "label": "MG2",
     "hierarchy": "SUPER2"
  },
  {
     "label": "SG1",
     "hierarchy": "SUPER3"
  }
]

Expected Output,

[
   {
     "label": "SUPER1",
     "options": [
      {
         "label": "AG1",
         "hierarchy": "SUPER1"
      },
      {
          "label": "AG2",
         "hierarchy": "SUPER1"
      }
    ]
   },
   {
      "label": "SUPER2",
      "options": [
      {
       "label": "MG1",
       "hierarchy": "SUPER2"
       },
       {
        "label": "MG2",
        "hierarchy": "SUPER2"
        }
      ]
      },
      {
         "label": "SUPER3",
         "options": [
          {
              "label": "SG1",
              "hierarchy": "SUPER3"
            }
         ]
        }
     ]

My code,

data.reduce((acc, item, i, array) => {
      acc = Object.keys(acc).length ? { ...acc, "label": item['hierarchy'], "options": acc.options ? 
       [...acc.options, item] : [item] } : { "label": item['hierarchy'], "options": [item] };
     return acc;
   }, {});

But with my code, the whole array is getting under 1 hierarchy.Can anyone help me with best way out getting the desired output. Thanks.

1 Answers

const input=[
  {
    "label": "AG1",
    "hierarchy": "SUPER1"
  },
  {
     "label": "AG2",
     "hierarchy": "SUPER1"
  },
  {
     "label": "MG1",
     "hierarchy": "SUPER2"
  },
  {
     "label": "MG2",
     "hierarchy": "SUPER2"
  },
  {
     "label": "SG1",
     "hierarchy": "SUPER3"
  }
]

const result =input.reduce((acc,curr)=>{
  if(acc[curr.hierarchy]){
    acc[curr.hierarchy].options.push(curr)
  }
  else {
   acc[curr.hierarchy] = { label: curr.hierarchy, options:[curr]};
  }
  return acc;
},{})
console.log(Object.values(result))
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related