【问题标题】:How to order by multiple date time properties with nulls last?如何按最后一个空值的多个日期时间属性排序?
【发布时间】:2018-10-02 16:00:43
【问题描述】:

我有一个 json,我想通过多个日期时间属性来订购这个 json。但是有一个 pinnedAt 属性指出该帖子必须位于顶部。顺便说一句,我正在使用 lodash。

这是我要解释的sql文档:

如果指定了 NULLS LAST,则空值排在所有非空值之后;如果指定了 NULLS FIRST,则空值排在所有非空值之前。如果两者都未指定,则在指定或隐含 ASC 时默认行为为 NULLS LAST,在指定 DESC 时为 NULLS FIRST(因此,默认行为就像空值大于非空值一样)。指定 USING 时,默认的 null 排序取决于运算符是小于还是大于运算符。

您可以在此处阅读更多内容:https://www.postgresql.org/docs/9.0/static/sql-select.html


这是我的示例数据:

{
  "data": [
    {
      "name": "Paris",
      "createdAt": "2018-10-01T08:28:05.074Z",
      "pinnedAt": null
    },
    {
      "name": "New York",
      "createdAt": "2018-10-01T05:16:05.074Z",
      "pinnedAt": null
    },
     {
      "name": "Washington",
      "createdAt": "2018-10-02T08:28:05.074Z",
      "pinnedAt": "2018-10-02T15:19:23.245Z"
    }
  ]
}

我要订购的代码

posts = _.orderBy(state.posts, ['pinnedAt', 'createdAt'], ['desc', 'desc']);

但这不像我想要的那样订购。这是我的预期

{
  "data": [
    {
      "name": "Washington",
      "createdAt": "2018-10-02T08:28:05.074Z",
      "pinnedAt": "2018-10-02T15:19:23.245Z"
    },
    {
      "name": "Paris",
      "createdAt": "2018-10-01T08:28:05.074Z",
      "pinnedAt": null
    },
    {
      "name": "New York",
      "createdAt": "2018-10-01T05:16:05.074Z",
      "pinnedAt": null
    }
  ]
}

我该怎么做?

谢谢。

【问题讨论】:

    标签: javascript sql-order-by lodash


    【解决方案1】:

    您可以使用自定义函数将null 视为可以正确排序的不同值。

    const data = [
        {
          "name": "Paris",
          "createdAt": "2018-10-01T08:28:05.074Z",
          "pinnedAt": null
        },
        {
          "name": "New York",
          "createdAt": "2018-10-01T05:16:05.074Z",
          "pinnedAt": null
        },
        {
          "name": "Washington",
          "createdAt": "2018-10-02T08:28:05.074Z",
          "pinnedAt": "2018-10-02T15:19:23.245Z"
        }
    ]; 
    
    const result = _.orderBy(data, 
                             [(item) => item.pinnedAt ? item.pinnedAt : "", 'createdAt'], 
                             ['desc', 'desc']);
    

    使用https://npm.runkit.com/lodash lodash 4.17.11 版测试


    这是有效的,因为空字符串“小于”任何其他字符串值。降序排序时,这将始终显示在列表的末尾。因为这些空字符串值是等价的,所以没有pinnedAt 的对象将按createdAt 排序,正如预期的那样。

    【讨论】:

      猜你喜欢
      • 2021-09-18
      • 2012-01-20
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多