Object loop with Jquery each

Asked

Viewed 721 times

1

I am looping an object with Jquery each and am not succeeding.

Object generated below via PHP:

{"status":"hasP",
 "flag":null,
 "qtProcess":null,
 "code": null,
 "message": [{"id":"1","email":"[email protected]"},{"id":"2","email":"[email protected]"}]}

Jquery code to capture the obejto and generate a table (part where it generates a failure):

$.each(data, function(index, value){                    
    table +='<tr><td>' + value.message.id + '</td>';
    table +='<td>' + value.message.email + '</td></tr>';
});

Generates the following error:

TypeError: value.message is undefined
  • Give a console.log(value) and see if there really is the message field; and since message is an array, it will not be possible to access the id directly as it is doing, it would have to be something like value.message[0].id

2 answers

3


You are not reading the object correctly, the array is in the attribute message:

var table = "";

var data =  {"status":"hasP","flag":null,"qtProcess":null,"code":null,"message":[{"id":"1","email":"[email protected]"},{"id":"2","email":"[email protected]"}]}

$.each(data.message, function(index, value){
  table +='<tr><td>' + value.id + '</td>';
  table +='<td>' + value.email + '</td></tr>';
});

console.log(table);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  • I only changed the code on the part placed by Glauber and it worked. $. each(data.message, Function(index, value){ table +='<tr><td>' + value.id + '</td>'; table +='<td>' + value.email + '</td></tr>'; });

  • @RRV you were wanting to loop the whole object, but the array is in the message attribute, which indicates an array are the brackets [ ] and the keys { } inside the brackets are the lines.

0

Accesses the object message directly into the object date with pure javascript.

for (index in data.message) {
        table +='<tr><td>' + index.id + '</td>';
        table +='<td>' + index.email + '</td></tr>';
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.