我收到如下 JSON 响应:
bills : [
{
id: '111',
date: '22 Jan 2020',
amount: -250.00
},
{
id: '222',
date: '08 Jan 2020',
amount: 700.00
},
{
id: '333',
date: '08 Feb 2020',
amount: -250.00
},
{
id: '788-609098-129169487',
date: '08 Feb 2020',
amount: 120.00
}
]
我想要一个仅包含日期
和金额
的对象,其中月
总计为金额
,如下所示:
{
"Jan" :
{
"month" : "Jan",
"amount" : 450.00
},
"Feb" :
{
"month" : "Feb",
"amount" : -130.00
}
}
如有任何帮助,我们将不胜感激。
最佳答案
const bills = [
{
id: '111',
date: '22 Jan 2020',
amount: -250.00
},
{
id: '222',
date: '08 Jan 2020',
amount: 700.00
},
{
id: '333',
date: '08 Feb 2020',
amount: -250.00
},
{
id: '788-609098-129169487',
date: '08 Feb 2020',
amount: 120.00
}
];
const output = bills.reduce((a, {date, amount}) => {
const month = date.slice(3, 6);
if(!a[month]) {
a[month] = {"month": month, amount}
} else {
a[month].amount += amount ;
}
return a;
}, {});
console.log(output);
关于javascript - 从 JSON 响应创建对象并删除不需要的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61064170/