1

I have this ajax call which its result is in a 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 is the result

$users_arr = array();
//After a successful query from my 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 the C.L-1 returns true but the C.L-2 returns undefined. I thought the data returned is an array on it's own so I want to run a for loop for each user like this

for(var i = 0; data.length > i; i++){
    eachUser = data[i];
    userInfo = eachUser.split(',');
    userId = userInfo[0]; // and so on for the other info
    $('div#age'+userId).html(userAge);
}

But the problem is that the data.length returns undefined which prevents me for running my for loop. Please any better help?

Edit here are some data from C.L-1

Object {8: "8,debbie,23", 3: "3,doggie,20", 7: "7,dini,22"}
doggie brezy
  • 289
  • 3
  • 16

1 Answers1

2

With a 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 to the 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 is to know that you can use the next two options only when the keys start from 0.

You can count the elements in your object like this:

var obj = {
  0: "8,debbie,23",
  1: "3,doggie,20",
  2: "7,dini,22"
};
var wrong_count = obj.length; //this will return undefined
var correct_length = Object.keys(obj).length; //this will return 3
console.log(wrong_count);
console.log(correct_length);

for(var i = 0; i < correct_length; i++){
  console.log(obj[i]);
}

For more info about Object.keys() you can refer to this link.

Another alternative to that would be to use a 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 i = 0; i < another_count; i++){
  console.log(obj[i]);
}
Ionut Necula
  • 11,107
  • 4
  • 45
  • 69