I have a need for a list type object simultaneously providing the contrary JS array behaviours of being iterable and associative. So at one point I want to run an index based walk through the members and in another I want to do 'does this key exist' and 'update the data under that key'.
I see many question in SO regarding discussions about associative arrays but this question differs because I am seeking re-usable code that wraps both behaviours. The solution can be a modifier to the array prototype, or a stand-alone object creation function. I accept that the list must be unique by key, and FYI in my case the members will be objects themselves.
Please note I know that there is no such thing as an associative array in JavaScript - I don't need that sermon. I seek the a solution for a single object with both capabilities on the same list.
Here is a rudimentary version in a working snippet. I am looking for a more fleshed out version that includes the full set of life-cycle features such as disposal, etc..
var List = function() {
this.elements={} // assoc list of elements.
this.elementArray=[] // plain array
this.addElement=function (id, member) {
this.elements[id]=member;
this.elementArray.push(member);
}
}
var myList = new List();
myList.addElement('V', {id: 'key2', name: 'Volvo'});
myList.addElement('A', {id: 'key4', name: 'Apple'});
myList.addElement('S', {id: 'key3', name: 'Google'});
console.log('Via iteration');
for (var i = 0; i < myList.elementArray.length; i = i + 1) {
console.log('id=' + myList.elementArray[i].id + ' name=' + myList.elementArray[i].name);
}
console.log('Via association');
console.log('Value of A: id=' + myList.elements['A'].id + ' name=' + myList.elements['A'].name);
console.log('Value of V: id=' + myList.elements['V'].id + ' name=' + myList.elements['V'].name);
console.log('Value of S: id=' + myList.elements['S'].id + ' name=' + myList.elements['S'].name);