按日期排序时,空值不起作用JSON对象。

时间:2018-07-12 23:09:06

标签: javascript json sorting

对不起,我是javascript的新手,但我目前正在尝试根据属性对JSON对象进行排序,但现在无法对其进行排序。

例如:我尝试这样做:

function sortByKey(array, key)
{

  return array.sort(function(a, b) {
  let x = a[key];
  let y = b[key];
  x = new Date(a.dateModified);
  y = new Date(b.dateModified);
  return x>y ? -1 : x<y ? 1 : 0;
});
}

然后我尝试根据“ lastCompletedEvaldate”进行排序:

[
  {
    "_id": "<a MongoDB object ID>",
    "name": "Fred Flintstone",
    "email": "fflintstone@hotmail.com",
    "sex": "male",
    "tags": [
      "foo",
      "bar"
    ],
    "lastCompletedEvalDate": "2018-05-14 12:02:14.955",
    "pendingEvalSentDate": null,
    "pendingEvalViewedEmailDate": null,
    "pendingEvalClickedLinkDate": null

  },
  {
    "_id": "<a MongoDB object ID>",
    "name": "Barney Rubble",
    "email": "barney@gmail.com",
    "sex": "intersex",
    "tags": [],
    "lastCompletedEvalDate": "2018-05-14 12:02:14.954",
    "pendingEvalSentDate": "2018-05-14 12:02:14.955",
    "pendingEvalViewedEmailDate": "2018-05-14 12:02:14.955",
    "pendingEvalClickedLinkDate": "2018-05-14 12:02:14.955"

  },
  {
    "_id": "<a MongoDB object ID>",
    "name": "Bambam Rubble",
    "email": "bam@bam.com",
    "sex": null,
    "tags": [
      "baz"
    ],
    "lastCompletedEvalDate": "2018-05-14 12:02:14.955",
    "pendingEvalSentDate": null,
    "pendingEvalViewedEmailDate": null,
    "pendingEvalClickedLinkDate": null
  }
]

但是,当我像这样使用函数时:

let temp = sortByKey(file, 'lastCompletedEvalDate');

并使用get请求将其输出:

router.get('/dash/participant', function(req, res){
  res.send(temp);
});

我仍然得到未排序的相同输出。难道我做错了什么。

3 个答案:

答案 0 :(得分:2)

如果有可行的选择,则应始终避免使用内置的日期解析器(请参见Why does Date.parse give incorrect results?)。在这种情况下,字符串“ 2018-05-14 12:02:14.955”与ECMA-262中的格式不一致,因此实现可能返回无效的日期(而Safari确实如此)。

由于日期字符串将按字符串排序,因此请使用 localeCompare 而不是创建Date对象:

function sortByKey(array, key) {
  return array.sort((a,b) => a[key].localeCompare(b[key]));
}

var data = [{
    "lastCompletedEvalDate": "2018-05-14 12:02:14.955",
    "pendingEvalSentDate": null,
  },
  {
    "lastCompletedEvalDate": "2018-05-14 12:02:14.954",
    "pendingEvalSentDate": "2018-05-14 12:02:14.955",
  },
  {
    "lastCompletedEvalDate": "2018-05-14 12:02:14.955",
    "pendingEvalSentDate": null,
  }
];

sortByKey(data, 'lastCompletedEvalDate');

console.log(data)

答案 1 :(得分:1)

在代码中,您通过implicit忽略dateModified对数组进行排序。尝试关注

key

我用简单的字符串比较替换了function sortByKey(array, key) { return array.sort((a, b) => -(a[key] > b[key]) || +(a[key] < b[key]) ); } ,请参见下面的注释。

此外,new Date确实可以进行排序,因此,要保留原始数组,您可能首先要克隆它:

Array.prototype.sort

答案 2 :(得分:0)

您可以尝试以下操作:

function sortByKey(array, key)
{ 
   return array.sort((a, b) => 
      new Date(a[key]) - new Date(b[key])
   ) 
}

您还可以签入documentation