1

how can I loop through these items?

var userCache = {};
userCache['john']     = {ID: 234, name: 'john', ... };
userCache['mary']     = {ID: 567, name: 'mary', ... };
userCache['douglas']  = {ID: 42,  name: 'douglas', ... };

the length property doesn't work?

userCache.length

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Blankman: What this does is set prop to each key contained with the object, in a loop. So prop will be "john", "mary", "douglas", etc. (in no defined order, it depends on the Javascript implementation and the direction of the wind that day). Thus, inside the loop, you can do alert(userCache[prop].name) to get the name property of each of the objects stored in the cache.
0
for(var i in userCache){
   alert(i+'='+userCache[i]);
}

Comments

0

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.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.