我有这个对象,我想返回一个升序排序的新对象,同时考虑到作为ISOString的startTime。 (我也在用片刻)我该怎么做?
{{1}}
答案 0 :(得分:3)
以下内容将按照开始时间升序对诊所进行排序。
Object.values()
将对象属性值转换为数组来工作。 Array.prototype.sort()
将值按升序排序。Array.prototype.reduce()
创建了一个新对象。
const clinics = {
"a0CW00000027OX3MAM": {
"id": "a0CW00000027OX3MAM",
"companyName": "Hendrick Medical Center",
"startTime": "2018-08-10T05:30:00.000Z",
},
"a0CW00000026gjJMAQ": {
"id": "a0CW00000026gjJMAQ",
"companyName": "ABC Manufacturing",
"startTime": "2018-08-10T10:36:00.000Z",
},
"a0CW00000026gipMAA": {
"id": "a0CW00000026gipMAA",
"companyName": "ABC Manufacturing",
"startTime": "2018-08-01T10:36:00.000Z",
}
};
const sorted = Object.values(clinics)
.sort((a, b) => a.startTime > b.startTime)
.reduce((m, c) => m.set(c.id, c), new Map());
for (let [key, value] of sorted.entries()) {
console.log(key, value);
}
编辑-答案已更新为使用Map
,以确保属性排序。
答案 1 :(得分:2)
对象不是数组,因此如果不先将其转换为数组就无法对其进行真正的排序。这是一个将其转换为数组然后仅使用字段文本进行排序的示例,因为ISO会很好地进行排序。
编辑,我对其进行了更新,以添加将其转换回对象的功能
add