无法对最接近当前日期的json对象进行排序,并且未定义某些值

时间:2011-12-06 04:21:34

标签: javascript json sorting

我从Facebook收到一个包含一些朋友信息的json对象。

有些用户已经包含了他们的生日有些没有,而有些用户仅包括月和日。

我想对数组进行排序,使用户首先关闭当前日期的生日。

我该怎么做?

json对象如下所示:

json = { "data" : [{name : "Joe Sam", id : "5555555", birthday: "02/02/1989" }, {name : "Joe Sam", id : 5555555, birthday:  }, {name : "Joe Sam", id : 5555555, birthday: "01/01" }

1 个答案:

答案 0 :(得分:1)

您的JSON无效 - 如果这是实际的JSON字符串,则需要引用键名。你已经关闭了结束]和},并且中间记录的生日必须有某种价值,例如空字符串或空 - 或者根本就不提供该密钥。我假设您可以解决这个问题,并且已经将JSON解析为名为json的变量。

另外你没有说日期是DD / MM(/ YYYY)格式还是MM / DD(/ YYYY)格式,所以我会为DD / MM编码,但是你可以注释出来使用MM /而不是DD。

“最接近当前日期”含糊不清:昨天比下周更接近?我将假设昨天离你当前的日期还很远。

所以这里的对象与排序例程一起整理。我没有对它进行过测试,但即使假设它已经破了,也应该给你一般的想法:

var json = { "data" : [
                {name : "Joe Sam", id : "5555555", birthday: "02/02/1989" },
                {name : "Joe Sam", id : 5555555, birthday: null },
                {name : "Joe Sam", id : 5555555, birthday: "01/01" }
             ]
           };

// First sort into ascending birthday order, with people who didn't provide
// a birthday at the beginning of the list

function dayMonthComparer(a,b)
  // note double-equals null also allows for undefined "birthday" property 
  if (aBD == null)
    return bBD == null ? 0 : -1;

  if (bBD == null)
    return 1;

  // next two lines allow for DD/MM format; comment them out for MM/DD format
  aBD = aBD.substr(3,2) + aBD.substr(0,2);
  bBD = bBD.substr(3,2) + bBD.substr(0,2);

  // note: simple string compare works once in MM/DD format
  return aBD === bBD ? 0 : (aBD > bBD ? 1 : -1);
}

json["data"].sort(function(a,b) {
  return dayMonthComparer(a["birthday"],b["birthday"]);
});

// Next, find the first item in the array after the current date and
// move everything before that item to the end of the array.
var today = new Date(),
    d = today.getDate(),
    m = today.getMonth() + 1,
    current,
    firstNonBlank = null,
    firstFromCurrent = 0;

if (d < 10) d = "0" + d;
if (m < 10) d = "0" + d;

current = d + "/" m;
// or use current = m + "/" + d if using American format

// get index of first item with birthday on or after current date
while(firstFromCurrent < json["data"].length &&
      dayMonthComparer(current,json["data"][firstFromCurrent]["birthday"]) > 1) {
  if (firstNonBlank===null &&
      json["data"][firstFromCurrent]["birthday"] != null)
     firstNonBlank = firstFromCurrent;
  firstFromCurrent++;
}

if (firstFromCurrent < json["data"].length) {
  json["data"] = json["data"].slice(firstFromCurrent)
                 .concat(json["data"].slice(firstNonBlank,firstFromCurrent),
                         json["data"].slice(0,firstNonBlank) );
}

// array is now sorted by birthday starting from current date, where
// those who didn't provide a birthday are at the end

有关.sort()工作原理的详细信息,请参阅MDN doco