javascript - 按月份和日期的总值对数组进行排序 - Angular
问题描述
我有这种类型的 json 数据,我需要在给定日期按月对这些数据进行排序,并使用总计算值。
[
{
"value": "123",
"date": "01/01/2020"
},
{
"value": "342",
"date": "12/01/2020"
},
{
"value": "432",
"date": "23/01/2020"
},
{
"value": "123",
"date": "01/02/2020"
},
{
"value": "123",
"date": "01/01/2020"
},
{
"value": "322",
"date": "16/02/2020"
},
{
"value": "643",
"date": "26/02/2020"
}
]
我想在新数组中对这样的新数据进行排序
[
{
"value": "1020", // total count of values
"date": "Jan" // month in string
},
{
"value": "1088", // total count of values
"date": "Feb" // month in string
}
]
我正在使用 moment.js 转换日期
提前致谢
解决方案
const data = [{"value":123,"date":'01/01/2020'},{"value":342,"date":'12/01/2020'},{"value":432,"date":'23/01/2020'},{"value":123,"date":'01/02/2020'},{"value":123,"date":'01/01/2020'},{"value":322,"date":'16/02/2020'},{"value":643,"date":'26/02/2020'}];
const toDate = str => new Date(str.replace(/^(\d+)\/(\d+)\/(\d+)$/, "$2/$1/$3"));
const month = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
const map = data.reduce((a,b) => {
const m = toDate(b.date).getMonth();
a[m] = a[m] ? +a[m]+b.value : +b.value;
return a;
}, {});
const res = Object.entries(map).map(([key, value]) => ({value, date: month[+key]}))
console.log(res)