0

I have a JSON array which is returned from my PHP ajax call. I need to loop through it and display all the information. I can not seem to get a method working. I am used to using the foreach key => value, in PHP but that doesn't seem to be an option here.

my array is

[{"Type":"Person","Durable":"Durable","Url":"test.com"},
{"Type":"Person","Durable":"Durable","Url":"test2.com"},
{"Type":"Person","Durable":"Durable","Url":"test3.com"},
{"Type":"Person","Durable":"Durable","Url":"test4.com"},
{"Type":"Location","Durable":"Durable","Url":"test5.com"},
{"Type":"Phone","Durable":"Durable","Url":"test6.com"}]

The length of the array changes every time it is not always 6 items. And the loop is going to go in my success handler. I just need help on how to access the data.

success: function(data){

}
2
  • 1
    for (var i in data) { ... } should work. You would reference an array item with data[i] Commented Feb 4, 2015 at 20:53
  • I know that it is, but everywhere else I saw I found crazy amount of different ways and i couldnt get any to work Commented Feb 4, 2015 at 20:58

3 Answers 3

1

You can use a simple loop statement:

   success: function(data){
    var i, l;
    for (i = 0, l = data.length; i < l; i++) { 
        // access the object: data[i]
        console.log(data[i]);
    }
  }

This is the most effiecient way.

Sign up to request clarification or add additional context in comments.

5 Comments

This is the most effiecient way - based on what?
And why do you use two variables in your for loop?
l is defined only once. If you done something like data.length withn the evaulation, it is computed each time
What if i needed to display the data in a special location. How could i access it like data[Type] as a variable
you just do data[i].Type .. data[i].Durable .. etc.. This solution is a bit faster than forEach and also works on older browsers.
0

You can just loop through the array:

success: function(data){
  for (var i = 0; i < data.length; i++) { 
    var obj = data[i];
    var type = obj.Type;
    var durable = obj.Durable;
    var url = obj.Url;
    // do work
  }
}

Comments

-1

You can use the array prototype forEach:

data.forEach(function(item) {
    var type = item["Type"];
    var durable = item["Durable"];
    /*...*/
});

2 Comments

forEach is not supported natively on some older browsers like IE8
This is what I need to access the data how i want, thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.