有人可以帮助我如何使用lodash groupby实现以下输入到所需的输出吗?我尝试了其他链接中讨论的lodash groupby方法,但无法实现预期的输出。 输入:
inputList: dataMaster[] = [
{
"isSelected": true,
"GroupKey": "G1",
"GroupName": "Group1",
"Key": "Key1",
"Name": "Key Name 1"
},
{
"isSelected": true,
"GroupKey": "G1",
"GroupName": "Group1",
"Key": "Key2",
"Name": "Key Name 2"
},
{
"isSelected": true,
"GroupKey": "G2",
"GroupName": "Group2",
"Key": "Key1",
"Name": "Key Name 1"
},
{
"isSelected": true,
"GroupKey": "G2",
"GroupName": "Group2",
"Key": "Key2",
"Name": "Key Name 2"
}
预期输出如下:
outputList: dataGroup[] = [
{
GroupKey:"G1",
GroupName:"Group1",
Group:[
{
Key:"Key1",
Name:"Key Name 1"
},
{
Key:"Key2",
Name:"Key Name 2"
}
]
},
{
GroupKey:"G2",
GroupName:"Group2",
Group:[
{
Key:"Key1",
Name:"Key Name 1"
},
{
Key:"Key2",
Name:"Key Name 2"
}
]
}
]
答案 0 :(得分:1)
您在这里:
// Change as necessary for your module loading configuration
import _ = require("lodash");
let grouped1 = _.groupBy(inputList, (dm) => dm.GroupKey);
let outputList: dataGroup[] = Object.keys(grouped1).map((groupKey) => {
let groupItems = grouped1[groupKey];
return {
GroupKey: groupKey,
GroupName: groupItems[0].GroupName,
Group: groupItems.map((dm) => _.pick(dm, "Key", "Name"))
};
});
如果您对此有任何疑问,请告诉我。