How to iterate over a JSON Object

It's easy to loop through the keys of a JavaScript associative array (hash):

var words = {
    'a': 'apple',
    'b': 'boy',
    'c': 'car',
    'd': 'dog'
}

for(var key in words) {
    if(words.hasOwnProperty(key)) {
        alert(words[key]);
    }
}

The hasOwnProperty() method makes sure that your key does not exist as a result of inheritance (i.e. via the object's prototype).

What if I don't use hasOwnProperty?

If you have any code that extends the base Object's prototype:

Object.prototype.myFunction = function() {
};

var words = {
    'a': 'apple',
    'b': 'boy',
    'c': 'car',
    'd': 'dog'
}

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

then you will be looping over functions, etc. that exist in the base Object's prototype.

This will be alerted:

a web page showing an alert dialog that prints out function text

when that's probably not what you want.

Comments

Leave a comment

What color are green eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.