From https://codereview.stackexchange.com/questions/25858/json-lookup-by-key
I have the following which works:
var data = [
{
"Key": "2222-2222-2222",
"Email": "a@test.com"
},
{
"Key": "1111-1111-1111",
"Email": "test@test.com"
}
],
lookup = {};
// generate the lookup table for reuse
data.forEach(function (el, i, arr) {
lookup[el.Key] = el.Email;
});
// returns 'test@test.com'
print(lookup['1111-1111-1111']);
What I want to do is(pushing works, accessing does not):
pushing(test data population):
var list = [];
for(someCount){
var uniqueID = uuidv4();
var objToAdd = {};
var objChild = {};
objChild.var1 = 1;
objChild.var2 = 2;
objToAdd[uniqueID] = objChild;
list.push(objToAdd);
}
read/access:
var var1Val = list[uniqueID].var1
or
for(var i = 0; i < list.length; i++){
if(list[i] === uniqueID){
var var1Val = list[i].var1
}
}
Also whats the proper way to check:
if(list[uniqueID] === undefined)
I'm trying to compare the performance of using a property name as an key for a look up table, opposed to a loop, as the array could have 1000's of elements and be accessed 1000's of times per second.
Edit: After a bit more research powered by the answers of Adrian Brand and CertainPerformance, It became clear I was trying to create a associative array using a actual Array, which javascript does not support. It seems though you can add named arrray elements but you can not access them by name, only by integer. (beware, I believe I read this leads to unexpected states)
As shown below the only option is to use a plain object. Surprisingly is very performant.
Also interesting post on 'undefined': Detecting an undefined object property
Wish I could select both Adrian Brand and CertainPerformance answers as they both helped immensely.