【问题标题】:Sort array by date in underscore.js在 underscore.js 中按日期对数组进行排序
【发布时间】:2020-07-22 09:41:39
【问题描述】:

我正在使用 Coffescript、underscore.js、knout,并且我正在尝试按日期对数组进行排序,但由于某种原因它无法正常工作

let accounts = [
  {
    id: 101,
    content: "abc1",
    createdDate: "2015-12-22T00:00:00"
  },
  {
    id: 102,
    content: "abc2",
    createdDate: "2012-12-22T00:00:00"
  }

]

这就是我在coffeescript中编写代码的方式

_.sortBy(accounts, (a) ->  a.createdDate)

同样在 JS 中生成的代码

return this.accounts(_.sortBy(accounts, function(a) {
      return a.createdDate;
    }));

请让我知道我哪里出错了。我没有收到任何错误,但数组没有按日期排序。

【问题讨论】:

    标签: javascript asp.net knockout.js coffeescript underscore.js


    【解决方案1】:

    您的 JSON 语法无效并且没有 createdDate 属性,应该是这样的:

    accounts = [
      {
        id: 102,
        content: "abc",
        createdDate: "2015-12-22T00:00:00"
      }
    ]
    

    所以你可以使用你写的函数(使用=>而不是->)。

    工作示例:

    let accounts = [
      {
        id: 101,
        content: "abc1",
        createdDate: "2015-12-22T00:00:00"
      },
      {
        id: 102,
        content: "abc2",
        createdDate: "2012-12-22T00:00:00"
      },
      {
        id: 103,
        content: "abc3",
        createdDate: "2018-12-22T00:00:00"
      }
    ]
    
    accounts = _.sortBy(accounts, (a) =>  a.createdDate)
    console.log(accounts)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

    当然,idcontent 只是一个例子。

    【讨论】:

    • 我给出的数据只是一个例子。我从一个对象中获取我的数据,JSon 是这样的 { id: 101, content: "abc", createdDate: "2015-12-22T00:00:00" }
    • 好的,那么我认为唯一的问题是- 符号而不是=,请查看更新后的答案。
    • 是的,我试过了,我输入了 '=' 而不是 '-',还是不行。
    • 请在问题中包含确切的问题和错误信息。
    • @Techno 您是否将sortBy 的结果分配回原始数组? sortBy 不会改变原始数组。 @Tamas 在他们的回答中这样做了,但你可能错过了:accounts = _.sortBy(accounts, (a) =&gt; a.createdDate)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 2021-02-23
    • 2016-09-30
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多