我尝试使用此对象数组对对象数据进行分组:
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 }
];
将所有对象的所需输出格式获取到新数组中:
[
{
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 }]
}
];
我尝试使用reduce函数,但它不是我得到的所需格式:
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;
}, []);
qq_花开花谢_0
长风秋雁
至尊宝的传说
慕丝7291255
相关分类