Anyone ever need to hash by object reference in javascript?
Maybe you want to group the children of ul
s by a hash of their DOM nodes, or attributes by instances of constructed objects, or many other things.
I have read this and don't want to use Weakmaps until they're stable.
The only way I can think to do it is storing parents in an array and enforcing reference uniqueness there, then hashing by the index of the reference in the array. (example is finding all the common UL parents of LIs):
var lis = document.getElementsByTagName('li'); // Get all objects
var parent, key, li;
for (var i=0; i<lis.length; i++ ) { // For every LI
storeItemByParent(lis[i], lis[i].parentNode);
}
var parents = [];
var itemsByParent = {};
function storeItemByParent (item, parent){
var key;
// Does this parent already exist? if so, use that index as the hash key
for (var j=0; j<parents.length; j++) {
if(parents[j] === parent) {
key = j;
break;
}
}
// This is a new parent? If so, track it and use that index as the hash key
if (key == undefined) {
parents.push(parent);
key = parents.length;
}
// Finally! The lis in a hash by parent "id".
itemsByParent[key] = itemsByParent[key] || [];
itemsByParent[key].push(item);
}
Is there a better way to store attributes or children or other things attached to an object instance without adding them as properties of the object itself?