Reputation: 2140
Is there a way to iterate over every property of an object using the Prototype JavaScript framework?
Here's the situation: I am getting an AJAX response in JSON that looks something like this:
{foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}
If I evaluate that json response in to a variable response
, I want to be able to iterate over each property in the response.barobj
object to see which indexes are true and which are false.
Prototype has both Object.keys()
and Object.values()
but oddly seems to not have a simple Object.each()
function! I could take the results of Object.keys() and Object.values() and cross-reference the other as I iterate through one, but that is such a hack that I am sure there is a proper way to do it!
Upvotes: 90
Views: 106468
Reputation: 211982
You have to first convert your object literal to a Prototype Hash:
// Store your object literal
var obj = {foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}
// Iterate like so. The $H() construct creates a prototype-extended Hash.
$H(obj).each(function(pair){
alert(pair.key);
alert(pair.value);
});
Upvotes: 42
Reputation: 169563
There's no need for Prototype here: JavaScript has for..in
loops. If you're not sure that no one messed with Object.prototype
, check hasOwnProperty()
as well, ie
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
doSomethingWith(obj[prop]);
}
Upvotes: 555
Reputation: 113310
You should iterate over the keys and get the values using square brackets.
See: How do I enumerate the properties of a javascript object?
EDIT: Obviously, this makes the question a duplicate.
Upvotes: 0