无法访问$ .each中的对象属性

时间:2015-10-20 16:05:16

标签: javascript jquery ajax

在ajax请求返回一个对象后,我执行$.each'原因我需要读取返回的所有对象(约会)。但似乎在$ .each中,对象是未定义的,我不知道为什么。这是我的每个请求的代码:

$.each(response.appointments, function(index, appointment)
{
      var event = 
      {
           'id': appointment['id'],
           'title': appointment['service']['name'] + ' - ' 
                  + appointment['customer']['first_name'] + ' ' 
                 + appointment['customer']['last_name'],
           'start': appointment['start_datetime'],
           'end': appointment['end_datetime'],
           'allDay': false,
           'color': '#' +  appointment['res_id']['hex_color'],
           'data': appointment  
      };
      calendarEvents.push(event);
});

这是console.log(响应)中返回的response对象的内容:

enter image description here

和约会结构:

enter image description here

有人有想法解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

如果我正确地阅读了您的对象图片(请在下次包含实际文字),response是一个数组对象,每个对象都包含约会。在这种情况下,您想说:

$.each(response, function(index, rsp) {
  $.each(rsp.appointments, function(index, appointment)
  {
      var event = 
      {
           'id': appointment['id'],
           'title': appointment['service']['name'] + ' - ' 
                  + appointment['customer']['first_name'] + ' ' 
                 + appointment['customer']['last_name'],
           'start': appointment['start_datetime'],
           'end': appointment['end_datetime'],
           'allDay': false,
           'color': '#' +  appointment['res_id']['hex_color'],
           'data': appointment  
      };
      calendarEvents.push(event);
  })
});

答案 1 :(得分:1)

我认为你错误地引用了你的对象 - 试试这个:

$.each(response, function(index, item) {
    $.each(item.apointments, function(idx2, appointment) {
         ....