如何在javascript对象中分组和创建新属性?

时间:2019-03-24 19:49:13

标签: javascript

我在javascript中有一个对象:

 "types": [
    {
      "ProcessCode": "b4919f5a-98cf-e711-80f3-1458d0431600",
      "ProcessName": "processX",
      "DocumentCode": 1,
      "DocumentName": "doc1"
    },
    {
      "ProcessCode": "b4919f5a-98cf-e711-80f3-1458d0431600",
      "ProcessName": "processX",
      "DocumentCode": 2,
      "DocumentName": "doc2"
    },
    {
      "ProcessCode": "b4919f5a-98cf-e711-80f3-1458d0431600",
      "ProcessName": "processX",
      "DocumentCode": 4,
      "DocumentName": "doc4"
    },
   {
      "ProcessCode": "09c27913-98cf-e711-80f3-1458d0431600",
      "ProcessName": "processY",
      "DocumentCode": 1,
      "DocumentName": "doc1"
    },
    {
      "ProcessCode": "09c27913-98cf-e711-80f3-1458d0431600",
      "ProcessName": "processY",
      "DocumentCode": 2,
      "DocumentName": "doc2"
    }
]

如何按ProcessCode将该对象分组以使其看起来像这样?

"types": [
    {
      "ProcessCode": "b4919f5a-98cf-e711-80f3-1458d0431600",
      "ProcessName": "processX",
      "Docs": [{
        "DocumentCode": 1,
        "DocumentName": "doc1"
        },
        {
        "DocumentCode": 2,
        "DocumentName": "doc2"
        },
        {
        "DocumentCode": 4,
        "DocumentName": "doc4"
        }
     ]
   },
   {
      "ProcessCode": "09c27913-98cf-e711-80f3-1458d0431600",
      "ProcessName": "processY",
      "Docs": [{
        "DocumentCode": 1,
        "DocumentName": "doc1"
       },
       {
        "DocumentCode": 2,
        "DocumentName": "doc2"
       }
     ]
   }
 }
]

我曾经尝试过使用lodash的groupBy,但是它把ProcessCode作为键,而不像我想要的结构那样。

 "types": [
    {
     "b4919f5a-98cf-e711-80f3-1458d0431600": {...

1 个答案:

答案 0 :(得分:1)

您可以使用功能reduce进行分组,并使用功能Object.values提取分组的对象。

let types = [    {      "ProcessCode": "b4919f5a-98cf-e711-80f3-1458d0431600",      "ProcessName": "processX",      "DocumentCode": 1,      "DocumentName": "doc1"    },    {      "ProcessCode": "b4919f5a-98cf-e711-80f3-1458d0431600",      "ProcessName": "processX",      "DocumentCode": 2,      "DocumentName": "doc2"    },    {      "ProcessCode": "b4919f5a-98cf-e711-80f3-1458d0431600",      "ProcessName": "processX",      "DocumentCode": 4,      "DocumentName": "doc4"    },   {      "ProcessCode": "09c27913-98cf-e711-80f3-1458d0431600",      "ProcessName": "processY",      "DocumentCode": 1,      "DocumentName": "doc1"    },    {      "ProcessCode": "09c27913-98cf-e711-80f3-1458d0431600",      "ProcessName": "processY",      "DocumentCode": 2,      "DocumentName": "doc2"    }];

let result = Object.values(types.reduce((a, {ProcessCode, ProcessName, DocumentCode, DocumentName}) => {
  (a[ProcessCode] || (a[ProcessCode] = {ProcessCode, ProcessName, Docs: []})).Docs.push({DocumentCode, DocumentName});
  return a;
}, Object.create(null)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }