im trying to group my data of objects using this array of objects:
var data = [
{ IdUser: 8, Name: "John Smith", transferType: 'download', total: 6 },
{ IdUser: 12, Name: "Jane Smith", transferType: 'download', total: 15 },
{ IdUser: 11, Name: "Joe Smith", transferType: 'download', total: 20 },
{ IdUser: 12, Name: "Jane Smith", transferType: 'upload', total: 7 },
{ IdUser: 11, Name: "Joe Smith", transferType: 'upload', total: 16 },
{ IdUser: 8, Name: "John Smith", transferType: 'upload', total: 12 }
];
to get this desired output format of all objects into new array:
[
{
IdUser: 8,
Name: 'John Smith',
download: [{ IdUser: 8, Name: "John Smith", transferType: 'download', total: 6}],
upload: [{ IdUser: 8, Name: "John Smith", transferType: 'upload', total: 12 }]
},
{
IdUser: 12,
Name: 'Jane Smith',
donwload: [{ IdUser: 12, Name: "Jane Smith", transferType: 'download', total: 15 }],
upload: [{ IdUser: 12, Name: "Jane Smith", transferType: 'upload', total: 7 }]
},
{
IdUser: 11,
Name: 'Joe Smith',
download: [{ IdUser: 11, Name: "Joe Smith", transferType: 'download', total: 20 }],
upload: [{ IdUser: 11, Name: "Joe Smith", transferType: 'upload', total: 16 }]
}
];
I have tried to use reduce function but its not the desired format that im getting:
data.reduce(function (a, b) {
a[b.Name] = a[b.Name] || [];
a[b.Name]["IdUser"] = b.IdUser;
a[b.Name][b.transferType] = a[b.Name][b.transferType] || [];
a[b.Name][b.transferType].push(b);
return a;
}, []);