0

I've called some data from php using AJAX, and the result if I code alert(data.a) looks like this...

({a:[{my_id:"34", name:"Dave"}, {my_id:"39", name:"Barry"}]} 

I'm not sure how to loop through this to extract the values.

My latest code...

for (var key in data.a)
{
 if (data.a.hasOwnProperty(key))
 {
   alert(key + " -> " + data.a[key]);
 }
}

... displays

0 -> [object Object]

and this displays the same too...

for (var i=0,  tot=data.a.length; i < tot; i++)
{
  for (var key in data.a[i]) 
  {
    if (data.a[i].hasOwnProperty(key))
    {
      alert(key + " -> " + data.a[i][key]);
    }
  }
}

What's the trick to looping through these results to extract the data for display?

If it helps, here's what I send at the end of my php...

$x['a'] = $myArray; 
echo json_encode($x);

Thanks for your time and help.

4
  • console.log(data.a); and you will know the structure Commented Apr 7, 2014 at 13:09
  • 1
    Alerting for debugging purpose is not recommended. Alerting an object will print [object ObjectName]. Use console.log. Your second loop is right! Commented Apr 7, 2014 at 13:10
  • Not able to reproduce the problem. Please check this jsfiddle.net/5xnUS Commented Apr 7, 2014 at 13:11
  • 1
    jsfiddle.net/Wf8LU ? Commented Apr 7, 2014 at 13:12

4 Answers 4

2

Are you after something like this? Loop through all the objects the print out all of their properties and values?

for (var i = 0; i < data.a.length; i++) {
    var objectInArray = data.a[i];
    var keys = Object.keys(objectInArray);
    for (var j = 0; j < keys.length; j++) {
        var key = keys[j];
        alert(key  + " -> " + objectInArray[key]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

When you are doing data.a[key] in for loop, you are getting a json object: {my_id:"34", name:"Dave"} for key = 0, and {my_id:"39", name:"Barry"} for key = 1. So in order to get values you should do something like this:

for (var key in data.a)
{
  if (data.a.hasOwnProperty(key))
  {
     alert(key + " -> " + data.a[key].my_id);
     // data.a[key].name to get name attribute
  }
}

Comments

1

Is it just

for (var i=0; i < data.a.length; i++) {
  alert(data.a[i].my_id + " -> " + data.a[i].name);
}

Comments

1

In your example, data.a is an array of objects, so this would work:

for (var i = 0; i < data.a.length; i++) {
  console.log('my_id: ' + data.a[i].my_id);
  console.log('name: ' + data.a[i].name);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.