views:

49

answers:

4

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  A: 

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.

Daniel Vassallo
+1 for `hasOwnProperty`
SLaks
+1 Although it *isn't* necessary to use `hasOwnProperty` if you've created the object via the Object constructor (e.g., `var useCache = {}` or `var userCache = new Object()`) and you're not extending `Object.prototype` (which would be a *really, really bad idea*). There's no harm it using it, though.
T.J. Crowder
@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.
T.J. Crowder
@T.J. Good point. I'll clarify my answer. :) ... Done
Daniel Vassallo
A: 
for(var i in userCache){
   alert(i+'='+userCache[i]);
}
Jage
A: 

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.

Sean Kinsey
A: 

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

see here for iterating over the properties.

http://stackoverflow.com/questions/1200562/difference-in-json-objects-using-javascript-jquery/1200713#1200713

lincolnk