我需要显示从firebase获得的数据数据。数据包含日期和值。数组如下
[{data:
{paidAmount: 850, purpose: "Medicine"}
date:
21/02/2018},
{data:
{paidAmount: 100, purpose: "Treatment"}
date:
21/02/2018},
{data:
{paidAmount: 400, purpose: "Medicine"}
date:
20/02/2018},
{data:
{paidAmount: 200, purpose: "Treatment"}
date:
21/02/2018}],
{data:
{paidAmount: 400, purpose: "Treatment"}
date:
10/02/2018}

在上面的数组中,存在3个相同的日期对象,我需要将3个对象作为1组成,其中date属性相同,数据属性为数组,如下所示: [{date:21/02/2018,数据:[{paidAmount:850,目的:" Medicine"}, {paidAmount:100,目的:"治疗"},{paidAmount:200,目的:"治疗"}]},{日期:20/02/2018,数据:{paidAmount: 400,目的:"医学"}]。 我该如何实现这一个? ,
答案 0 :(得分:0)
虽然这个问题与Angular或Typescript没有任何关系,但这是一个有效的解决方案:
const dataset = [
{
data: {
paidAmount: 850,
purpose: "Medicine"
},
date: '21/02/2018'
},
{
data: {
paidAmount: 100,
purpose: "Treatment"
},
date: '21/02/2018'
},
{
data: {
paidAmount: 400,
purpose: "Medicine"
},
date: '20/02/2018'
},
{
data: {
paidAmount: 200,
purpose: "Treatment"
},
date: '21/02/2018'
},
{
data: {
paidAmount: 400,
purpose: "Treatment"
},
date: '10/02/2018'
}
]
const hash = {};
dataset.forEach(x => {
if (!hash[x.date]) {
hash[x.date] = [x.data];
return;
}
hash[x.date].push(x.data);
});
const transformed = [];
for (date in hash) {
transformed.push({date, data: hash[date]});
}
console.log(transformed);