I have this array which is retrieved by a json_encode().When I execute
$.getJSON('beta.php' , function(data){
console.log(data);
});
I get the result as follows
[
Object { StuId="1", fName="Saman", more...},
Object { StuId="2", fName="Marry", more...},
Object { StuId="3", fName="Navjoth", more...},
Object { StuId="4", fName="Jassu", more...}
]
I'm trying to iterate through this result using
$.each(data, function(key, value){
for(var key in value){
if(value.hasOwnProperty(key)){
$("#article tbody").html(
"<tr><td>" + value.StuId +
"</td><td>" + value.fName +
"</td><td>" + value.lName +
"</td><td>" + value.age +
"</td><td>" + value.grade +
"</td></tr>");
$("article tbody").appendTo("document.body");
}
}
});
.I guess It is impossible because of the above format of the array.
If someone could explain why this is happening and how to correct it I would be really grateful.I want to know how to convert the above into the following format.
[
{"StuId":"1","fName":"Saman","lName":"Kumara","age":"14","grade":"A"},
{"StuId":"2","fName":"Marry","lName":"Vass","age":"12","grade":"B"},
{"StuId":"3","fName":"Navjoth","lName":"Bogal","age":"32","grade":"A"},
{"StuId":"4","fName":"Jassu","lName":"Singh","age":"22","grade":"E"}
]
You are overwriting the tables html with different values each time.
$(document).ready(function() {
var html = "";
var data = [
{ StuId:"1", fName:"Saman"},
{ StuId:"2", fName:"Marry"},
{ StuId:"3", fName:"Navjoth"},
{ StuId:"4", fName:"Jassu"}
]
$.each(data, function(key, value){
console.log(value + "--" + key);
html += "<div><span>" + value.StuId + "</span><span>" + value.fName + "</span></div>";
});
$('body').html(html)
});
Loops in JavaScript are different from other languages. You need closures.
Have a look here: