我有一个对象数组,其中包含日期属性。我希望按照本周的记录和上周的记录进行分组。使用javascript和moment.js实现此目的的最佳方法是什么。以下是数据集的结构。
const obj = [{
first_name: "Peter",
last_name: "Hansen",
date: "2018-01-01"
},
{ first_name: "Jonas",
last_name:"Da Vinci",
date: "2018-01-02"
},
{ first_name: "Ohmel",
last_name: "Reynolds",
date: "2018-01-03"
},
{ first_name: "Raisa",
last_name: "Johnson",
date: "2017-12-25"
},
{
first_name: "Karen",
last_name: "Anderson",
date: "2017-12-26"
},
{
first_name: "Kristina",
last_name: "Alvaro",
date: "2017-12-27"
}]
预期产出:
本周
上周
答案 0 :(得分:0)
您可以使用array#reduce
基于一周对数组进行分组。
const arr = [{ first_name: "Peter", last_name: "Hansen", date: "2018-01-01" }, { first_name: "Jonas", last_name:"Da Vinci", date: "2018-01-02" }, { first_name: "Ohmel", last_name: "Reynolds", date: "2018-01-03" }, { first_name: "Raisa", last_name: "Johnson", date: "2017-12-25"}, { first_name: "Karen", last_name: "Anderson", date: "2017-12-26" }, { first_name: "Kristina", last_name: "Alvaro", date: "2017-12-27" }];
var sortedByWeek = arr.reduce((res, {date, first_name, last_name}) => {
var startOfWeek = moment(date, 'YYYY-MM-DD').startOf('week').add(1,'days').format('YYYY-MM-DD');
res[startOfWeek] = res[startOfWeek] || [];
res[startOfWeek].push(first_name + ' ' + last_name);
return res;
},{});
console.log(sortedByWeek);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>