Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 254
Allie the Icon Avatar asked Feb 25 '09 21:02

Allie the Icon


People also ask

Which line of code is used to iterate through all the properties of an object?

The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.

Which loop is used to iterate the properties of an object?

The for/in loop statement is used to iterate a specified variable over all the properties of an object.

Can you iterate through an object JavaScript?

Object. It takes the object that you want to loop over as an argument and returns an array containing all properties names (or keys). After which you can use any of the array looping methods, such as forEach(), to iterate through the array and retrieve the value of each property.


1 Answers

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]); } 
like image 185
Christoph Avatar answered Oct 05 '22 15:10

Christoph