Monday, February 26, 2024
 Popular · Latest · Hot · Upcoming
171
rated 0 times [  178] [ 7]  / answers: 1 / hits: 106084  / 15 Years ago, wed, february 25, 2009, 12:00:00

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!


More From » prototypejs

 Answers
209

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);
});

[#99929] Wednesday, February 18, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
teagan

Total Points: 98
Total Questions: 106
Total Answers: 101

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
teagan questions
Fri, Mar 5, 21, 00:00, 3 Years ago
Mon, Feb 15, 21, 00:00, 3 Years ago
;