retrograde
retrograde

Reputation: 2979

using .each to loop through Json Response

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);

Upvotes: 12

Views: 15633

Answers (5)

Cutting Edge Hobbies
Cutting Edge Hobbies

Reputation: 99

This worked for me

success : function(json) {
    var obj = JSON.parse(JSON.stringify(json));
        display = obj;
            $.each(display, function(i) {
                alert(display[i].secretQuestion);
            });
}

Upvotes: -1

Sumant
Sumant

Reputation: 134

This should do the trick for you

$.each(display.data,function(i,member){
    console.log(member.id+":"+member.company_name);
});

You need to iterate over data object instead of display object.

Fiddle Link:- Demo

Upvotes: 2

Random Identity
Random Identity

Reputation: 305

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);
      }
    }
  }
}

Upvotes: 6

Akash Rajbanshi
Akash Rajbanshi

Reputation: 1593

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

Upvotes: 6

AmmarCSE
AmmarCSE

Reputation: 30557

company_name is a nested property.

You can access it like

$.each(display, function(i, member) {
    if (i == 'data') {
        console.log(display[i][0]['company_name']);
    }
});

or if you use $.each on the display['data'] array itself

$.each(display['data'], function(i, member) {
    console.log($(this)[0]['company_name']);
});

var display = {
    "total": 134,
    "per_page": 15,
    "current_page": 1,
    "last_page": 9,
    "from": 1,
    "to": 15,
    "data": [{
        "id": "89",
        "company_name": "test"
    }]
};

$.each(display, function(i, member) {
    if (i == 'data') {
        console.log(display[i][0]['company_name']);
    }
});

$.each(display['data'], function(i, member) {
    console.log($(this)[0]['company_name']);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Upvotes: 2

Related Questions