views:

9395

answers:

4

I have a JSON object like the following

 var p =
    {
        "p1": "value1",
        "p2": "value2",
        "p3": "value3"
    };

Now I want to loop through all p elements (p1,p2,p3...) and get their key and values. How can I do that? I can modify the Json object if necessary . My ultimate goal is to loop through some key value pairs. And if possible I want to avoid using eval.

A: 
for(key in p) {
  alert(key);
}

Note: you can do this over arrays, but you'll iterate over the length and other properties, too.

Richard Levasseur
When using a for loop like that, `key` will just take on an index value, so that will just alert 0, 1, 2, etc... You need to access p[key].
Bryan
+2  A: 

You can just iterate over it like:

for (var key in p) {
  alert(p[key]);
}

Note that key will not take on the value of the property, it's just an index value.

Bryan
+35  A: 

You can use the for-in loop as shown by others. However, you also want to make sure that the key you get is an actual property of an object, and doesn't come from the prototype:

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    alert(key + " -> " + p[key]);
  }
}
levik
+1 for using hasOwnProperty
Andreas Grech
+2  A: 

You have to use the for-in loop

But be very careful when using this kind of loop, because this will loop all the properties along the prototype chain.

Therefore, when using for-in loops, always make use of the hasOwnProperty method to determine if the current property in iteration is really a property of the object you're checking on:

for (prop in p) {
    if (!p.hasOwnProperty(prop)) {
        //The current property is not a direct property of p
        continue;
    }
    //Do your logic with the property here
}
Andreas Grech