我有一个包含startDate的对象数组。对象不是按startDate顺序排列的。我想创建一个新数组,并将共享同一startDate的所有对象归为单独的对象。
highlight()
使用angular.forEach我尝试遍历所有对象,获取startDate值,将该值添加到新数组中,然后将当前对象添加到具有匹配日期的数组中。我找不到将当前事件对象添加到新数组(eventDays)中与我的eventIndex变量匹配的索引处的对象中的解决方案。
var eventArray = [
{
eventName: "event1",
startDate: "2018/08/01", // YYYY/MM/DD
id: 1
},
{
eventName: "event2",
startDate: "2018/08/03",
id: 2
},
{
eventName: "event3",
startDate: "2018/08/01",
id: 3
},
{
eventName: "event4",
startDate: "2018/08/06",
id: 4
}
];
我正在寻找的结果是这样的。
let eventDays = [];
let eventIndex = 0;
angular.forEach(eventArray, function(event){
let day = event.startDate;
if(eventDays.length == 0){
eventDays.push({
dateGroup: day,
event
});
}
else {
if(event.startDate == eventDays[eventIndex].groupDay) {
// insert event object into eventDays[eventIndex] after dateGroup, event
}
else if(event.startDate !== eventDays[eventIndex].groupDay){
eventDays.push({
dateGroup: day,
event
});
eventIndex++;
}
}
});
这样可能吗?
尼娜是对的,我不能重复使用名称键名。我需要在对象内创建另一个数组来存储我要传递的对象。该代码段有效。
eventDays = [
{
groupDate: "2018/08/01",
event: {
eventName: "event1",
startDate: "2018/08/01",
id: 1
},
event: {
eventName: "event3",
startDate: "2018/08/01",
id: 3
}
},
{
groupDate: "2018/08/03",
event: {
eventName: "event2",
startDate: "2018/08/03",
id: 2
}
},
{
groupDate: "2018/08/06",
event: {
eventName: "event4",
startDate: "2018/08/06",
id: 4
}
}
];
答案 0 :(得分:2)
您可以使用Map
来对同一startDate
进行分组,并比包含对象的数组进行渲染。
var eventArray = [{ eventName: "event1", startDate: "2018/08/01", id: 1 }, { eventName: "event2", startDate: "2018/08/03", id: 2 }, { eventName: "event3", startDate: "2018/08/01", id: 3 }, { eventName: "event4", startDate: "2018/08/06", id: 4 }],
result = Array.from(
eventArray.reduce((m, o) => m.set(o.startDate, (m.get(o.startDate) || []).concat(o)), new Map),
([groupDate, events]) => ({ groupDate, events })
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
尼娜是对的,我不能重复使用名称键名。我需要在对象内创建另一个数组来存储我要传递的对象。该代码段有效。
angular.forEach($scope.events, function (event) {
if ($scope.eventDays.length == 0) {
$scope.eventDays.push({
'groupDate': event.startDate,
'events': [event]
});
} else {
if (event.startDate == $scope.eventDays[eventIndex].groupDate) {
$scope.eventDays[eventIndex].events.push(event)
} else if (event.startDate !== $scope.eventDays[eventIndex].groupDate) {
$scope.eventDays.push({
'groupDate': event.startDate,
'events': [event]
});
eventIndex++;
}
}
});