如何在 angular 8 中的对象数组中进行分组

How to do grouping in Array of Objects in angular 8

如何对一组对象进行分组?是否可以在以下情况下使用reduce?

例如:如果同样需要将数据单独附加到一个字段中,我需要将 id 和 name 分组。

[{
data: ["Sriram Krishnan", 1440]
id: "CHARSUR"
name: "CHARSUR"
},
{
data: ["shaleesh ", 2955]
id: "Timesheet"
name: "Timesheet"
},
{
data:["Balachander ", 3720]
id: "CHARSUR"
name: "CHARSUR"
},
{
data: ["Sriram Krishnan", 720]
id: "Aroscop"
name: "Aroscop"
},
{
data: ["Karthik ", 540]
id: "Timesheet"
name: "Timesheet"
},
{
data: ["Shaju Murugan", 420]
id: "CHARSUR"
name: "CHARSUR"
}]

预期结果: 我需要将分组的结果(数据)追加到数组的数组中。

[{
data: [["Sriram Krishnan", 1440],["Balachander ", 3720],["Shaju Murugan", 420]]
id: "CHARSUR"
name: "CHARSUR"
},
{
data: [["shaleesh ", 2955],["Karthik  ", 540]]
id: "Timesheet"
name: "Timesheet"
},
{
data: ["Sriram Krishnan", 720]
id: "Aroscop"
name: "Aroscop"
}]

我正在以这种方式形成数据以在 highcharts 饼图中使用。

在您的源数据中,请确保对象字段以逗号分隔:

src = [
    {
        data: ['Sriram Krishnan', 1440],
        id: 'CHARSUR',
        name: 'CHARSUR',
    },
    {
        data: ['shaleesh ', 2955],
        id: 'Timesheet',
        name: 'Timesheet',
    },
    {
        data: ['Balachander ', 3720],
        id: 'CHARSUR',
        name: 'CHARSUR',
    },
    {
        data: ['Sriram Krishnan', 720],
        id: 'Aroscop',
        name: 'Aroscop',
    },
    {
        data: ['Karthik ', 540],
        id: 'Timesheet',
        name: 'Timesheet',
    },
    {
        data: ['Shaju Murugan', 420],
        id: 'CHARSUR',
        name: 'CHARSUR',
    }];

此 JavaScript 代码将产生预期的分组结果:


let dst = [];

function getRecordInDst(srcRecord) {
    for (let dstRecord of dst) {
        if (dstRecord.id === srcRecord.id) return dstRecord;
    }
    let newRecord = {id: srcRecord.id, name: srcRecord.name, data: []};
    dst.push(newRecord);
    return newRecord;
}

for (let record of src) {
    getRecordInDst(record).data.push(record.data);
}