Iterating over every property of an object in javascript using Prototype?

JavascriptPrototypejs

Javascript Problem Overview


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!

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAllie the IconView Question on Stackoverflow
Solution 1 - JavascriptChristophView Answer on Stackoverflow
Solution 2 - JavascriptKenan BanksView Answer on Stackoverflow
Solution 3 - JavascriptCan Berk GüderView Answer on Stackoverflow