使用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
做了几次不成功的尝试。
您可以使用Object.keys()
简单地迭代对象,然后按属性日期对sort
进行排序(解析为Date
):
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
字符串后面的逗号不是必需的。
更新添加了其他排序条件。