onlineracoon
onlineracoon

Reputation: 2970

javascript jQuery get object key

I have the following code:

!function($){

    $.keys = {
        backspace: 8,
        tab: 9,
        enter: 13,
        escape: 27,
        space: 32,
        pageUp: 33,
        pageDown: 34,
        end: 35,
        home: 36,
        left: 37,
        up: 38,
        right: 39,
        down: 40,
        delete: 46,
        numpadEnter: 108,
        comma: 188
    };

}(window.jQuery);

And I want to build a function that returns a string of a key code for example:

$.keys.toString = function(key){
  switch(key){
    case $.keys.backspace:
      return 'backspace';
  }
};

The list would ofcourse be bigger, and support all the keys of the $.keys object. But is there a possibility that the $.keys.toString function actually uses the $.keys array to convert the int to string, so I don't have to make a switch statement.

Something like getKeyFromObjectValue?

Thanks for help :)

Upvotes: 1

Views: 2776

Answers (2)

onlineracoon
onlineracoon

Reputation: 2970

$.keys.toString = function(key){
    $.each($.keys, function(key, value){
        if(value === key){
            return key;
        }
    });
};

Thanks for help :)

Upvotes: 1

pimvdb
pimvdb

Reputation: 154968

Since the list of keys is constant, you could simply create another list by iterating and reversing:

$.keysReversed = {};
$.each($.keys, function(key, value) {
  $.keysReversed[value] = key;  // value as key, key as value
});

Now, $.keysReversed contains of number/name pairs. This is faster than doing magic each time you call .toString - you can just return $.keysReversed[key].

Upvotes: 5

Related Questions