12

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);
1
  • sorry, my answer was incorrect at first. It should be good now Commented May 24, 2015 at 4:18

5 Answers 5

6

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

Sign up to request clarification or add additional context in comments.

3 Comments

your answer looks very straightforward and works in the demo. But my alert now returns: {"members":"{\"total\":134,\"per_page\":15,\"current_page\":1,\"last_page\":9,\"from\":1,\"to\":15,\"data\": ... am I constructing the json object wrong?
sorry about the link...you can check your validity of json here : jsonlint.com
thank you for the help. Your solution worked, once I sorted out my json construction issues. Your help is very much appreciated!
6

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

Comments

2

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>

4 Comments

when I try either option, console shows: {"members":"{\"total\":134,\"per_page\":15,\"current_page\":1,\"last_page\":9,\"from\":1,\"to\":15,\"data\": ...
Maybe the problem is how Im constructing my json? I'll edit my question to show that
@retrograde, if you run the snippet in my answer, it should show: test
@retrograde, yes, it may have to do with how the json is constructed
2

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

Comments

-1

This worked for me

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.