简体   繁体   English

如何遍历 JavaScript 中的数组元素?

[英]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,预计 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.但是使用我的代码,整个数组都在 1 个层次结构之下。任何人都可以帮助我以最佳方式获得所需的 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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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