Search code examples
javascriptjqueryobject-literal

reversing an object literal?


I have a jQuery plugin where one of the options ('inits') the user can pass in is an array

the array can contain any of these values

space, tab, enter, comma

Now I have an object literal called keys that looks like

keys: {
        backspace: 8,
        enter:     13,
        space:     32,
        comma:     44,
        tab:       9
    }

I have a keydown handler

in the keydown handler I want to check if the key that was pressed is in the inits array. Now to do this I need to first map the key backwards in the keys array so I can get the name from the code.

How would I do this?


Solution

  • var keyName = ""
    for( var key in keys ){ if( keys[key] == keyCode ){ keyName = key } }
    
    if( $.inArray( keyName, inits ) != -1 ){ //do something }