使用.each循环遍历Json Response

ret*_*ade 11 each jquery json

我试图用.each()循环一个json对象,但我正在努力使语法正确.

Ajax调用,导致"未定义":

$('.showGroup a').on('click', function(e) {
e.preventDefault();
    var _href = $(this).attr("href");
     $.ajax({
       dataType: 'json',
       url : _href,
       type : 'GET',
       success : function(response) {
          $("#replace").empty();
          display = response;
        $.each(display, function(i, member) {
            alert(display[i].company_name);
        });
     },
    error : function() {
        console.log('error');
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

如果我只是呼叫警报(显示[i]); 我的json对象看起来像这样:

{"total":134,"per_page":15,"current_page":1,"last_page":9,"from":1,"to":15,"data":[{"id":"89","company_name":"test" ...
Run Code Online (Sandbox Code Playgroud)

我也尝试嵌套另一个.each()循环,但我得到了响应:未捕获TypeError:无法使用'in'运算符来搜索'17381'

我已经查看了几个SO答案并尝试了各种样式的.each循环,但我总是得到一个未定义的错误.

我错过了什么?

编辑 我在后端构建像这样的json:

$members = $this->user->getMemberIds($loggedIn->id, $display, $associationFilter);
           $this->arrResponse['members'] = $members->toJson();
return Response::json($this->arrResponse);
Run Code Online (Sandbox Code Playgroud)

Aka*_*shi 5

您可以通过这种方式访问​​每个循环:

$.each(display, function (i, member) {
for (var i in member) {
    alert("Company Name: " + member[i].company_name);
 }
});
Run Code Online (Sandbox Code Playgroud)

DEMO


小智 5

我认为更好的方法是使用vanilajs(纯javascript),因为与vanilajs for循环相比,jQuery $ .each非常慢.所以我已经提供了一个可行的样本,如果您对解决方案有任何疑问,请告诉我.

这是一个例子,常规javascript(因此vanilajs循环)执行的速度有多快https://jsperf.com/jquery-each-vs-for-loop/6

var i = 0,
  j = 0;
var items = [{
  "total": 55,
  "to": 22,
  "data": [{
    "id": "89",
    "company_name": "CompanyName 1"
  }, {
    "id": "89.1",
    "company_name": "CompanyName 1.1"
  }]
}, {
  "total": 51,
  "to": 22,
  "data": [{
    "id": "90",
    "company_name": "CompanyName 2"
  }, {
    "id": "90.1",
    "company_name": "CompanyName 2.1"
  }]
}];

var isEmpty = function(variable) {
  return variable === undefined || variable === null || variable === '' || variable.length === 0;
}


// jquery foreach is very slow, 
// it is always recommended to use valinajs for loop(where jQuery is not necessary)

for (i = 0; i < items.length; i++) {
  if (isEmpty(items[i].data) === false) {
    // data exist
    for (j = 0; j < items[i].data.length; j++) {
      if (isEmpty(items[i].data[j].company_name) === false) {
        // company exist
        console.log(items[i].data[j].company_name);
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)