简体   繁体   中英

iterating through array of objects with jquery

I am trying to iterate through data on success in an AJAX call. The data, when logged in console looks like this:

[Object, Object]
0: Object
  messages: Array[0]
  sid: 534
__proto__: Object
1: Object
   messages: Array[0]
   sid: 535

The javascript I am using is this:

 function startMsgCheck() {
    msgCheck = setInterval(function() {
    $.ajax({
      url: '/sepanel/chat/check_for_msg',
      type:'POST',
      dataType: "json",
      success: function(data) {
        console.log(data);
        $.each([data], function(i, val){
          var SID = data[i].sid
          if ( data[i].messages.message_id == $('#chat_message_ID_' + SID).val()) {
            return false;
          }
          else {
            var buildMsg = '<p><b>' + data[i].messages.name + '</b>(' + data[i].messages.time_stamp + ')<b>:</b> ' + data[i].messages.message + '</p>'

            $('#chat_messageID_' + SID).val(data[i].messages.message_id).text();

              $(buildMsg).appendTo("#tab-" + SID);

            $("#tab-" + SID).prop({ scrollTop: $("#tab-" + SID).prop("scrollHeight") });
            if (data.name == data[i].messages.agent_name){
              return false;
            }
            else {
            $('#li_' + SID).removeClass('active');
            $('#li_' + SID).removeClass('inactive');
            $('#li_' + SID).addClass('notify');
            }
          }
        });
      }
    });
    }, 1000);
   }

The problem I am having is that this is only working properly for the first object in the array. I can access the values for the [0] object but its not going through [1] ( or [2],[3] etc - when those objects exist).

I may be confused about this being an array at all, is the data coming back actually an object of objects? should I be using $.each at all ot should this be a for loop? if it should be a for loop how would I implement that? I am not sure what I am doing wrong, so if anyone can steer me in the right direction I would appreciate that.

Based on the console output, it looks like the data variable has this structure:

var data = [
    {
        messages: [...],
        sid: 1
    },{
        messages: [...],
        sid: 2
    }
];

Given this structure, you can iterate over it like this:

$.each(data, function(i, val) {
    var sid = val.sid;

    $.each(val.messages, function(j, message) {
        // do something with message
    });
});

the issue was the [] brackets around data in the each loop. Solution by pointy in the comments to the initial question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM