Reputation: 475
Hi guys I'm new to JS so my question seems to be trivial for you. I want to rewrite $.each() loop to for loop
Here is my code:
var students=[
{
"roll": 101,
"name": "Ben",
"emailId":"[email protected]"
},
{
"roll": 102,
"name": "Ian",
"emailId":"[email protected]"
},
{
"roll": 103,
"name": "Caroline",
"emailId":"[email protected]"
}
];
$.each(students,function(i,v){
$('p.listofstud').append(v.roll + " " + v.name + " " + v.emailId + "<br/>");
});
When I rewrite it i got [object Object] all properties are in one line (I prefer each three properties in one line).
for (var i=0,len=students.length;i<len;i++) {
for (var property in students) {
$('p.listofstud').append(students[property] + " ");
}
}
Can you help me please, thx in advance :)
Upvotes: 0
Views: 122
Reputation: 560
When referencing your students
array in the for loop, you should be referencing students[i]
, just as in the append parameter list should be students[i][property]
for (var i = 0, len = students.length; i < len; i++){
for (var key in students[i]){
$('p.listofstud').append(students[i][key] + " ");
}
$('p.listofstud').append("<br/>");
}
At the end of each loop you'll want to add a linebreak, as that will give you the desired format of having each students' parameters in a seperate row.
The problem with the original in students
form was that you were trying to get the keys in the array of students, and not the array of one given student.
Upvotes: 1