简体   繁体   中英

How to iterate through elements of an array in JavaScript?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM