Skip to content Skip to sidebar Skip to footer

How To Loop Through Items In A Js Object?

how can I loop through these items? var userCache = {}; userCache['john'] = {ID: 234, name: 'john', ... }; userCache['mary'] = {ID: 567, name: 'mary', ... }; userCache['dou

Solution 1:

You can loop over the properties (john, mary and douglas) of your userCache object as follows:

for (var prop in userCache) {
    if (userCache.hasOwnProperty(prop)) {
        // You will get each key of the object in "prop".// Therefore to access your items you should be using://     userCache[prop].name;//     userCache[prop].ID;//     ...
    }
}

It is important to use the hasOwnProperty() method, to determine whether the object has the specified property as a direct property, and not inherited from the object's prototype chain.

Solution 2:

for(var i in userCache){
   alert(i+'='+userCache[i]);
}

Solution 3:

For this you would use a for.. in loop

for (var prop in userCache) {
    if (userCache.hasOwnProperty(prop)) {
        alert("userCache has property " + prop + " with value " + userCache[prop]);
    }
}

The `.hasOwnProperty is needed to avoid members inherited through the prototype chain.

Solution 4:

there's no length property because you're not using an indexed array.

see here for iterating over the properties.

Difference in JSON objects using Javascript/JQuery

Post a Comment for "How To Loop Through Items In A Js Object?"