Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using .each to loop through Json Response

Tags:

json

jquery

each

I'm trying to loop through a json object with .each(), but I'm struggling with getting the syntax right.

Ajax Call, which results in "undefined":

$('.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');
    }
  });
});

if I just call alert(display[i]); my json object looks like this:

{"total":134,"per_page":15,"current_page":1,"last_page":9,"from":1,"to":15,"data":[{"id":"89","company_name":"test" ...

I have also tried to nest another .each() loop, but I get the response: Uncaught TypeError: Cannot use 'in' operator to search for '17381'

I have looked through several SO answers and tried various styles of .each loops, but I always get an undefined error.

What am I missing?

EDIT I am constructing json like this on backend:

$members = $this->user->getMemberIds($loggedIn->id, $display, $associationFilter);
           $this->arrResponse['members'] = $members->toJson();
return Response::json($this->arrResponse);
like image 987
retrograde Avatar asked May 24 '15 04:05

retrograde


2 Answers

You can access the each loop this way:

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

DEMO

like image 62
Akash Rajbanshi Avatar answered Oct 19 '22 17:10

Akash Rajbanshi


I think the better approach would be using vanilajs( pure javascript ) , because jQuery $.each very slow compare to vanilajs for loop. So I have given a sample it works and please let me know if face any problem understanding the solution.

Here is an example that how fast is regular javascript (thus vanilajs loop) performs 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);
      }
    }
  }
}
like image 42
Random Identity Avatar answered Oct 19 '22 18:10

Random Identity