1

我有这个对象:

  var eventsDates = new Array(
    "basket":"11-10-2012",
    "soccer":"21-10-2012",
    "soccer":"28-10-2012",
    "baseball":"25-11-2012",
    "baseball":"15-12-2012"
  );

我需要通过比赛提取日期,例如足球,而不是像这样保存结果

  var eventsDates = new Array(
    "21-10-2012",
    "28-10-2012"
  );

任何建议

卢卡

4

4 回答 4

1

看起来您是在建议您在数组中有一系列对象:

var events = [
    {"basket":"11-10-2012"},
    {"soccer":"21-10-2012"},
    {"soccer":"28-10-2012"},
    {"baseball":"25-11-2012"},
    {"baseball":"15-12-2012"}
];

var count = events.length, dates = [], m;

while (count--)
    if (m = events[count]["soccer"])
        dates.push(m);

console.log(dates);

小提琴:http: //jsfiddle.net/YX4Kq/

于 2012-10-17T14:32:52.587 回答
1

不要混合arrays使用objects其中一种:

var eventDates = [
   "11-10-2012",
   "21-10-2012",
   "28-10-2012",
   "25-11-2012",
   "15-12-2012"
];

或者

var eventDates = {
  "basket":"11-10-2012",
  "soccer":"21-10-2012",
  "soccer":"28-10-2012",
  "baseball":"25-11-2012",
  "baseball":"15-12-2012"
};

也就是说,您不能重复使用相同的密钥(如baseball),因此最好的结构将是以下之一:

var eventDates = {
  "basket": ["11-10-2012"],
  "soccer": ["21-10-2012", "28-10-2012"]
  "baseball": ["25-11-2012", "15-12-2012"]
};

并像访问eventDates.baseball

$.each(eventDates.baseball, function (k, v) {
  alert(v);
});

您也可以执行以下操作,但随后您将不得不使用自定义提取器,这将涉及在您只需要特定日期的任何时候迭代整个数组name

var eventDates = [
  {"name": "basket", "date":"11-10-2012"},
  {"name":"soccer", "date":"21-10-2012"},
  {"name": "soccer", "date":"28-10-2012",
  {"name": "baseball", "date":"25-11-2012"},
  {"name":"baseball", "date":"15-12-2012"}
];
于 2012-10-17T14:34:10.393 回答
0

对于此类任务,我会考虑使用不同的数据结构:

var eventDates = {
    Soccer: [{
         date: ...
    ]},
    Basket: [{
         date: ...
    ]}
};

然后您可以轻松访问 fe 所有足球日期:

for (var i = 0; i <= eventDates.Soccer.length; i++) {
    // Do something with eventDates.Soccer[i]
}
于 2012-10-17T14:29:29.437 回答
0
  var eventsDates = {
    "basket":["11-10-2012"],
    "soccer":["21-10-2012","28-10-2012"],
    "baseball":["25-11-2012","15-12-2012"]
  }


var soccerDates = eventsDates.soccer;
于 2012-10-17T14:30:51.823 回答