gpt4 book ai didi

javascript - 使用 Normalizr 后排序

转载 作者:行者123 更新时间:2023-11-29 20:58:40 24 4
gpt4 key购买 nike

在使用 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"]
},

现在我有一个按钮可以更改 iddate 之间的顺序。然后我需要更改 allIds(保留排序顺序)以按日期排序。 allIds 应如下所示:

allIds : ["comment2", "comment1", "comment3", "commment5", "comment4"] // sort by date

我不知道这个订单是怎么发出来的。我用 javascript sort 做了几次不成功的尝试。

最佳答案

您可以使用 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 字符串后的逗号不是必需的。

更新添加了另一个排序条件。

关于javascript - 使用 Normalizr 后排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47866752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com