javascript - How to get the length of a json returned data and run a for loop -
this question has answer here:
i have ajax call result in json format
$.ajax({ url: link, datatype: "json", success: function(data){ console.log(data); //c.l-1 console.log(data.length); //c.l-2 } })
and here result
$users_arr = array(); //after successful query database while($sql = mysqli_fetch_array($query)){ $user_id = $sql['id']; $user_age = $sql['age']; $user_name = $sql['name']; $users_arr[$user_id] = $user_id.','.$user_name.','.$user_age; } echo json_encode($users_arr);
now c.l-1 returns true c.l-2 returns undefined. thought data
returned array on it's own want run loop each user this
for(var = 0; data.length > i; i++){ eachuser = data[i]; userinfo = eachuser.split(','); userid = userinfo[0]; // , on other info $('div#age'+userid).html(userage); }
but problem data.length
returns undefined prevents me running loop. please better help?
edit here data c.l-1
object {8: "8,debbie,23", 3: "3,doggie,20", 7: "7,dini,22"}
with simple for ... in
loop:
var obj = { 7: "8,debbie,23", 8: "3,doggie,20", 9: "7,dini,22" }; for(var x in obj){ console.log(obj[x]); }
an alternative for in
loop can be:
var obj = { 7: "8,debbie,23", 8: "3,doggie,20", 9: "7,dini,22" }; object.keys(obj).foreach(function(key) { console.log(key, obj[key]); });
important know can use next 2 options when keys
start 0
.
you can count elements in object this:
var obj = { 0: "8,debbie,23", 1: "3,doggie,20", 2: "7,dini,22" }; var wrong_count = obj.length; //this return undefined var correct_length = object.keys(obj).length; //this return 3 console.log(wrong_count); console.log(correct_length); for(var = 0; < correct_length; i++){ console.log(obj[i]); }
for more info object.keys()
can refer link.
another alternative use for in
loop:
var obj = { 0: "8,debbie,23", 1: "3,doggie,20", 2: "7,dini,22" }; var another_count = 0; for(var x in obj){ another_count++; } console.log(another_count); for(var = 0; < another_count; i++){ console.log(obj[i]); }
Comments
Post a Comment