在使用Normalizr之后,我有这样一个数组:
comments : {
byId : {
"comment1" : {
id : "comment1",
author : "user2",
date: "2017-05-09 05:30:00",
comment : "....."
},
"comment2" : {
id : "comment2",
author : "user3",
date: "2017-04-19 04:30:00",
comment : "....."
},
"comment3" : {
id : "comment3",
author : "user3",
date: "2017-05-19 05:40:00",
comment : "....."
},
"comment4" : {
id : "comment4",
author : "user1",
date: "2017-08-06 05:30:00",
comment : "....."
},
"comment5" : {
id : "comment5",
author : "user3",
date: "2017-07-01 07:30:00",
comment : "....."
},
},
allIds : ["comment1", "comment2", "comment3", "commment4", "comment5"]
},现在,我有一个按钮可以在id或date之间更改顺序。然后,我需要将allIds (保留排序顺序)更改为按日期排序。allIds应该如下所示:
allIds : ["comment2", "comment1", "comment3", "commment5", "comment4"] // sort by date我不知道怎么能下这个订单。我用javascript sort做了几次失败的尝试。
发布于 2017-12-18 10:55:35
您可以简单地使用Object.keys()迭代对象,然后按属性日期(解析为Date)对sort进行排序:
var comments = {
byId: {
"comment1": {
id: "comment1",
author: "user2",
date: "2017-05-09 05:30:00",
comment: ".....",
},
"comment2": {
id: "comment2",
author: "user3",
date: "2017-04-19 04:30:00",
comment: ".....",
},
"comment6": {
id: "comment6",
author: "user3",
date: "2017-07-01 07:30:00",
comment: ".....485",
},
"comment3": {
id: "comment3",
author: "user3",
date: "2017-05-19 05:40:00",
comment: ".....",
},
"comment4": {
id: "comment4",
author: "user1",
date: "2017-08-06 05:30:00",
comment: ".....",
},
"comment5": {
id: "comment5",
author: "user3",
date: "2017-07-01 07:30:00",
comment: ".....",
},
},
allIds: ["comment1", "comment2", "comment3", "commment4", "comment5"]
};
var results = Object.keys(comments.byId).sort((s, a) => {
const date1 = Date.parse(comments.byId[s].date);
const date2 = Date.parse(comments.byId[a].date);
if (date1 === date2) {
return s.localeCompare(a);
}
return date1 - date2;
});
console.log(results);
参考文献:
注意:您忘记了date字符串后面的逗号。comment字符串后面的逗号是不必要的。
更新添加了另一个排序条件。
https://stackoverflow.com/questions/47866752
复制相似问题