To achieve a Dictionary in simple JavaScript is rather tricky, you would need to create an entire constructor to handle this - or use a library that would handle this for you.
By Dictionary I am refering to an object/hash that can use objects as keys. You would need a constructor that would use multiple arrays (one for the key and one for the value) and that would keep them in-sync. You could mimic many of the typical array methods, but as I stated this would be quite a bit of code.
As a simple alternative you can do the following:
function pushToObject(obj, key, value){
if( !key||!obj ) return false;
if( !key[''] ) {
pushToObject.index = pushToObject.index||[];
key[''] = pushToObject.index.length;
pushToObject.index.push(key);
}
obj[key['']] = value;
return true;
}
function removeFromObject(obj, key){
if( !isNaN(key) ) {
var list = listKeyObjects(obj);
var item = list[key];
return removeFromObject(obj,item);
}
else if(key) {
if( !key[''] ){
return false;
}
return delete obj[key['']];
}
return false;
}
function listKeyObjects(obj){
var a = [];
for(var i in obj){
a.push(pushToObject.index[i]);
}
return a;
}
usage
var array = {}; /// it would be best to change the name of this object
var an_object = {}, another_object = {};
/// add your items to the array object, this handles giving each of your
/// objects used as a key a unique index property. This does mean the objects
/// you use `an_object`, `another_object` are modified.
pushToObject( array, an_object, 'something else' );
pushToObject( array, another_object, 'something other than else' );
console.log(array); /// {0:'something else',1:'something other than else'}
removeFromObject( array, an_object ); /// remove using an object as a key
console.log(array); /// {1:'something other than else'}
removeFromObject( array, 0 ); /// remove using an offset index
console.log(array); /// {}
after thoughts
Obviously the better option is to create your own dedicated constructor for this, but you could improve the above with a bit more code so that it didn't modify the key objects. Instead whenever working with an object as a key you could scan the pushToObject.index
for the offset of your key object. I chose to go for the version that modifies your key objects however as it should function faster than having to scan a list every time you make an array modification.
get key function
The above code only shows you how to add and how to remove, it may also be a good idea on getting a particular key object from an offset:
function getKeyObjectAtIndex = function(obj, index){
var list = listKeyObjects(obj);
return list[index] ? list[index] : null;
}
console.log(array); /// {0:'something else',1:'something other than else'}
var key = getKeyObjectAtIndex(array, 1);
console.log(key === another_object) /// === TRUE