在javascript中找到地图中的键

时间:2014-05-10 10:17:25

标签: javascript map

如何从特定值的js map数组中找到键?例如:

var map = {'key1': 'value1', 'key2': 'value2'};

我如何找到value1的键?

1 个答案:

答案 0 :(得分:1)

Object.prototype.getKeyByValue = function( value ) {
    for( var prop in this ) {
        if( this.hasOwnProperty( prop ) ) {
             if( this[ prop ] === value )
                 return prop;
        }
    }
}

var test = {
   key1: 42,
   key2: 'foo'
};

test.getKeyByValue( 42 );  // returns 'key1'

来自:JavaScript object get key by value