linqts-按多个属性分组

时间:2019-03-21 13:29:29

标签: javascript typescript linq group-by linq.js

我有一个JSON对象数组,必须按多个属性进行分组。

const JSON_DATA = [
        {"componentName":"CP1","articleNumber":"441","componentType":"Ext","version":"V1.1.6"},
        {"componentName":"CP5","articleNumber":"444","componentType":"Int","version":"V2.1.8"},
        {"componentName":"CP5","articleNumber":"444","componentType":"Ext","version":"V2.1.0"},
        {"componentName":"CP5","articleNumber":"444","componentType":"Ext","version":"V2.1.8"},
        {"componentName":"CP4","articleNumber":"442","componentType":"Ext","version":"V1.1.0"}];

我想使用linqts按componentName,articleNumber和componentType分组。

interface IComponent {
  componentName: String;
  articleNumber: String;
  componentType: String;
  version: String;
}

class JsonGroupBy {
  public groupBy(data: IComponent[]): any {
    let mylist = new List < IComponent > (data);

    let result = mylist.GroupBy((comp) => comp.componentName, (comp) => comp.version);

    return result;
  }
}

这是可行的,但是我不知道如何不仅按componentName分组,而且按articleNumber和componentType分组。当前输出如下:

{"CP1": ["V1.1.6"], "CP4": ["V1.1.0"], "CP5": ["V2.1.8", "V2.1.0", "V2.1.8"]}

我更喜欢的结果是这样:

   
  [
    {"componentName": "CP1","articleNumber":"441","componentType":"Ext","version": ["V1.1.6"]},
    {"componentName": "CP5","articleNumber":"444","componentType":"Int","version": ["V2.1.8"]},
    {"componentName": "CP5","articleNumber":"444","componentType":"Ext","version": ["V2.1.0","2.1.8"]},
    {"componentName": "CP4","articleNumber":"442","componentType":"Ext","version": ["V1.1.0"]}
]

1 个答案:

答案 0 :(得分:2)

您可以收集版本并为每个组建立一个新的数据集。

const
    JSON_DATA = [{ componentName: "CP1", articleNumber: "441", componentType: "Ext", version: "V1.1.6" }, { componentName: "CP5", articleNumber: "444", componentType: "Int", version: "V2.1.8" }, { componentName: "CP5", articleNumber: "444", componentType: "Ext", version: "V2.1.0" }, { componentName: "CP5", articleNumber: "444", componentType: "Ext", version: "V2.1.8" }, { componentName: "CP4", articleNumber: "442", componentType: "Ext", version: "V1.1.0" }],
    result = Enumerable
        .From(JSON_DATA)
        .GroupBy(
            null,
            "$.version",
            "{ componentName: $.componentName, articleNumber: $.articleNumber, componentType: $.componentType, version: $$.ToArray() }",
            "[$.componentName, $.articleNumber, $.componentType].join('|')"
        )
        .ToArray();

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>