使用 Normalizr 后排序

Sort after using Normalizr

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

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