【问题标题】:Sorting json object by value按值排序json对象
【发布时间】:2014-06-09 15:40:25
【问题描述】:

我有一个如下所示的 json 对象,如何使用日期对其进行排序?

json = {"date_hash":{"second_bleed":"2014-09-08","sixth_boost":"2014-10-28","first_boost":"2014-06-24","first_bleed":"2014-08-08","fifth_boost":"2014-09-30","fourth_bleed":"2014-11-03","second_boost":"2014-07-15","fourth_boost":"2014-09-02","third_bleed":"2014-10-06","primary_injection":"2014-06-02","third_boost":"2014-08-05"}}

我试过了

json['date_hash'].sort(function(a, b){

});

排序不是json的函数吗?

【问题讨论】:

  • 它是一个对象,它没有顺序,不能排序
  • 看起来您想按某种顺序打印日期,所以首先将所有日期放入某个数组中并对其进行排序,我建议在将每个日期推入某个数组时,您可以在以下位置进行排序那个时候。
  • 没有 JSON 对象这样的东西。 JSON (JavaScript Object Notation) 是一个字符串。 “JSON 是一种完全独立于语言的 文本格式 ...”参见:json.org

标签: javascript jquery ruby-on-rails ajax json


【解决方案1】:

date_hash 对象是一个 JSON 对象,它没有顺序(不可排序)。

你应该尝试使用数组:

{"date_hash": [
    {"name": "second_bleed", "date": "2014-09-08"},
   ....
   {"name": "sixth_boost", "date": "2014-09-28"}
]}

然后是类似于你用来排序的函数。

function (a, b) {
    if (a.date < b.date) {
        return -1;
    } else if (a.date > b.date) {
        return 1;
    };
    return 0;
}

【讨论】:

    猜你喜欢
    • 2021-09-16
    • 2016-09-21
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 2018-02-18
    • 2013-04-06
    • 1970-01-01
    相关资源
    最近更新 更多