Learn many ways to iterate over an object properly in Javascript.

How to iterate over an Object with Javascript and jQuery optimally

Iterate over an array, such an easy task with a loop isn't ? But, do you know how to iterate over an object properly ?.

If you're a novice , you may learn it today and forget it tomorrow if your have chicken memory.

Javascript

The simplest way to iterate over an object with Javascript (and known) is to use a simple for .. in loop.

How it works is really simple, the for loop will iterate over the objects as an array, but the loop will send as parameter the key of the object instead of an index.

var OurObject = {
    testProperty: 123,
    anotherProperty: "Hey",
    helloWorld: "Hi"
};

for(var key in OurObject){
    // Check if the property really exists
    if(OurObject.hasOwnProperty(key)){
        var value = OurObject[key];
        // Do something with the item :
        // console.log(key,value);
    }
}

Note: we verify if the object really has the given property of the loop using hasOwnProperty to prevent the iteration of the prototype properties.

Or use a for loop as you always do, with an array that contains all the keys of the object using Object.keys :

var myObject = {"p1": "value1", "p2": "value2", "p3": "value3"};
// ["p1", "p2", "p3"]
var keys = Object.keys(myObject);

for(i = 0; i < keys.length; i++){
    var value = myObject[keys[i]];
    console.log(keys[i],value);
}

Now, if you want to iterate over all properties (even those that are not enumerable), you can use the following trick using the getOwnPropertyNames method (of the global Object available in the window) :

// Define a not enumerable property
var obj = Object.create({}, {
    // non-enumerable property
    getFoo: {
        value: function() { return this.foo; },
        enumerable: false
    }
});

obj.foo = "Hello";

Object.getOwnPropertyNames(obj).forEach(function (key) {
    var value = obj[key];
    console.log(key,value);
});

jQuery

With jQuery, use the $.each function which allow you to retrieve the index (key in the case of an object) and the value in a callback :

var obj = {
    myProperty: "Hello world !",
    not: "Yes",
    yes: "Nope",
    anotherProperty : {
        hi:"Hello"
    }
};

// or jQuery.each(...)
$.each(obj, function(key, value) {
    console.log(key, value);
});

Really simple isn't ?, however if you're working with huge objects, you may want to use Vanilla Javascript instead of jQuery as it is much faster.

jQuery vs for Loop


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors