简体   繁体   English

如何将 JS Array.sort() 与具有不同属性的对象一起使用

[英]How to use JS Array.sort() with objects with different properties

So I have these Objects:所以我有这些对象:

let obj1 = { from: Date, to: Date }
let obj2 = { date: Date }

They are in an Array:它们在一个数组中:

let arr = [ obj1, obj2 ]

Now I want to sort the objects inside the array with arr.sort().现在我想用 arr.sort() 对数组中的对象进行排序。 But I can't figure out how to use the property "from" for the object that has this property OR "date" for the other... I think there's an easy solution to that but I can't find anything related to this.但我不知道如何为具有此属性的 object 使用属性“来自”,或者为另一个使用“日期”...我认为有一个简单的解决方案,但我找不到与此相关的任何内容.

 let obj1 = { from: new Date(345635), to: new Date(454567) } let obj2 = { date: new Date(1230464) } let arr = [ obj1, obj2 ]; const sorted = arr.sort((a, b) => ((a.from || a.date) - (b.from || b.date))) console.log(sorted)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM