TypeScript中Angular项目不同对象数组合并后统一按日期排序问题
解决方案
你只需要调整排序逻辑,统一提取两个对象的对应日期字段作为排序依据即可,具体修改如下:
核心逻辑说明
两个数组的对象存储日期的字段不同,排序时先判断当前项的类型,取出对应的日期值再做比较:
- 预约对象(带
appointmentId)取appointmentDate作为排序日期 - 取消对象(带
cancelId)取cancelDate作为排序日期
修改后的完整代码
let appointments = this.appointmentService.getAppointmentsForJob(this.jobId); let cancellations = this.cancellationService.getCancellationsForJob(this.jobId); forkJoin([appointments, cancellations]).subscribe(results => { this.appointments = results[0]; this.cancellations = results[1]; this.loading = false; this.combinedItems = ([]).concat(this.appointments, this.cancellations); // 调整排序逻辑 this.combinedItems = this.combinedItems.sort((a, b) => { // 提取对应日期转时间戳比较 const dateA = (a.appointmentDate ?? a.cancelDate).getTime(); const dateB = (b.appointmentDate ?? b.cancelDate).getTime(); // 升序排列,如需降序改为 return dateB - dateA return dateA - dateB; }); console.log(this.combinedItems); });
TypeScript 类型安全优化(可选)
如果你的项目用了TypeScript,可以加类型守卫避免类型报错,写法更严谨:
// 提前定义联合类型 type Appointment = { appointmentId: number; appointmentDate: Date }; type Cancellation = { cancelId: number; cancelDate: Date }; type CombinedItem = Appointment | Cancellation; // 排序时的类型判断写法 this.combinedItems = (this.combinedItems as CombinedItem[]).sort((a, b) => { const getSortDate = (item: CombinedItem) => { if ('appointmentDate' in item) return item.appointmentDate.getTime(); return item.cancelDate.getTime(); } return getSortDate(a) - getSortDate(b); });
内容的提问来源于stack exchange,提问作者Robbie Mills
相关产品推荐
相关产品推荐

