Hash - a javascript dictionary object


    var yourHash = new Hash({foo: 'bar'});
    yourHash['key1'] = 'value';
    yourHash.key2    = 'value';

    var keys = yourHash.keys();
    for( i in keys ){
        alert( keys[ i ] );           // alerts 'key1', 'key2' and 'foo' in no given order
    	alert( yourHash[ keys[i] ] ); // alerts 'value', 'value' and 'bar' in no given order

    yourHash.values().join(', ')  == 'value, value, bar';

    yourHash.slice('key1', 'bad') == ['value', undefined];


The hash object works like a hash in Perl or a 'dictionary' generically. It is a group of name/value pairs where a unique name points to a unique value.

Why? Doesn't javascript's built-in Object() do the same?

Sure. But if you add a prototype such as keys or values to Object then that prototype will also exist on Array, String, Number and everything else, as everything else inherits the prototype of Object.

By creating a Hash object, we have a new place to add prototypes that will not inherit down the chain to objects where we have no need or want of it.


The code can be obtained from the head of this document. View source in your browser.


var hash = new Hash()
var hash = new Hash({ key: value, key: value })

The constructor takes zero or one arguments. The only allowed argument is another hash or a javascript object. this will be used to initialize the Hash.




Returns the complete list of keys (names) in the hash. There is no order to keys in a hash.



Returns the complete list of values in the hash, in no specific order


hash.slice(list, of, keys)

Returns a slice (subset) of values from the requested keys in the order of requested keys.


hash.concat( javascriptObject )
hash.concat({key: 'value', key2: 'value'})
hash.concat( anotherHash )

Concatenates a new list of key/value pairs onto the Hash. Keys that already exist will be overwritten by keys in the concatenated object. This method is useful for populating an empty Hash.


Support for this function is provided via ##javascript on freenode IRC.


Copyright © Rick Measham, 2006. All rights reserved.

This library is free software; you can redistribute it and/or modify it under the GPL or under the same terms as Perl at your discresion.


Rick Measham (aka Woosta)