Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a hashtable of json objects in javascript?

I want to create a hashtable of json objects, where each json object represents a user.

I want to do this to sort of create a client side 'cache' of users.

User { ID: 234, name: 'john', ..);

So I can then reference things like this:

if(userCache[userid] != null) alert(userCache[userid].ID);

is this possible?

like image 827
Blankman Avatar asked Feb 27 '23 01:02

Blankman


1 Answers

Javascript objects themselves are maps, so for instance:

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

// Usage:
var id = 'john';
var user = userCache[id];
if (user) alert(user.ID); // alerts "234"

(It wasn't clear to me whether your "userid" would be "john" or 234, so I went with "john" above, but you could use 234 if you preferred.)

It's up to the implementation how the keys are stored and whether the map is a hash map or some other structure, but I've done this with hundreds of objects and been perfectly happy with the performance, even on IE, which is one of the slower implementations (at the moment).

This works because there are two ways to get at the properties of a Javascript object: Via dotted notation, and via bracketed notation. For example:

var foo = {bar: 10};
alert(foo.bar);              // alerts "10"
alert(foo['bar']);           // alerts "10"
alert(foo['b' + 'a' + 'r']); // alerts "10"
s = "bar";
alert(foo[b]);               // alerts "10"

It may seem strange that this bracketed syntax for getting an object property by name is the same as getting an array element by index, but in fact, array indexes are object properties in Javascript. Property names are always strings (in theory), but auto-conversion occurs when you do things like user[234]. (And implementations are free to optimize-out the conversion if they can, provided the semantics are maintained.)

Edit Some bits and pieces:

Looping through the cache

And if you want to loop through the cache (and based on your follow-up question, you do, so perhaps others reading this question will want to too):

var key, user;
for (key in userCache) {
    // `key` receives the name of each property in the cache, so "john",
    // "mary", "douglas"...
    user = userCache[key];
    alert(user.ID);
}

The keys are looped in no defined order, it varies by browser.

Deleting from the cache

Suppose you want to delete a property from the cache entirely:

delete userCache['john'];

Now there is no longer a "john" property in the object at all.

like image 186
T.J. Crowder Avatar answered Mar 08 '23 06:03

T.J. Crowder