如何从特定值的js map数组中找到键?例如:
var map = {'key1': 'value1', 'key2': 'value2'};
我如何找到value1
的键?
答案 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'