Search code examples
javascriptarrayslookup-tables

How to use array of objects as lookup table based on property name


From https://codereview.stackexchange.com/questions/25858/json-lookup-by-key
I have the following which works:

var data = [
        {
            "Key": "2222-2222-2222",
            "Email": "[email protected]"
        },
        {
            "Key": "1111-1111-1111",
            "Email": "[email protected]"
        }
    ],
    lookup = {};

// generate the lookup table for reuse
data.forEach(function (el, i, arr) {
    lookup[el.Key] = el.Email;
});

// returns '[email protected]'
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.


Solution

  • Right now, you're pushing an object with a single uniqueID property to the array; list[someUniqueId] won't work, because a uniqueID would be a property of an item in the array, not the array itself. Just use an object instead:

    var listObj = {};
    for(someCount){
      var uniqueID = uuidv4();
      listObj[uniqueID] = {
        var1: 1,
        var2: 2,
      };
    }
    

    And then you can access with

    var var1Val = list[uniqueID].var1
    

    If you have indicies that you're always accessing the properties from (that is, uniqueIDs), probably best not to use an array anywhere in the code.

    Also whats the proper way to check:

    if(list[uniqueID] === undefind)
    

    Just change to undefined, and that should work just fine.