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
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

4 Answers4

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.

Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
  • @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 May 12 '10 at 16:08
0
for(var i in userCache){
   alert(i+'='+userCache[i]);
}
Jage
  • 7,990
  • 3
  • 32
  • 31
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.

Sean Kinsey
  • 37,689
  • 7
  • 52
  • 71
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

Community
  • 1
  • 1
lincolnk
  • 11,218
  • 4
  • 40
  • 61