A number of times (especially in MVC scenarios) I had to use an array to store objects, but I also had to access the objects by a property of the stored objects. I may then iterate the array, but I guess (guess because I really know little about Javascript performance) this will be slow already with hundreds of objects and hundreds of iterations. I then build an index like so:
var arr = [];
var index = {};
var o1 = {id: 0, key: "A", data: "X"};
var o2 = {id: 1, key: "B", data: "Y"};
arr.push(o1);
arr.push(o2);
index[o1.key] = o1;
index[o2.key] = o2;
var lookupKey = "B";
// modify object
arr[1].data = "Z";
// get data for key "B" - alerts "Z"
alert(index[lookupKey].data);
(http://jsfiddle.net/timvdh/WT53x/3/)
Of course I have to build and maintain this index... I was wondering if there is a better method?
I guess there is a lib that includes "SortedDictionaries" (the name of such generic collection in .NET) - and I would like to know about is. However, I am also working with specialized arrays (e.g. knockout's observableArray) and I would need a way to index that array, too. Or I need to know that it is simply not worth doing what I am doing with the index.