How to get a key in a JavaScript object by its val

2018-12-31 07:08发布

I have a quite simple JavaScript object, which I use as an associative array. Is there a simple function allowing me to get the key for a value, or do I have to iterate the object and find it out manually?

23条回答
若你有天会懂
2楼-- · 2018-12-31 07:40

with Underscore.js library:

var hash = {
 foo: 1,
 bar: 2
};

(_.invert(hash))[1]; // => 'foo'
查看更多
残风、尘缘若梦
3楼-- · 2018-12-31 07:40

No standard method available. You need to iterate and you can create a simple helper:

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'

One word of caution: Even if the above works, its generally a bad idea to extend any host or native object's .prototype. I did it here because it fits the issue very well. Anyway, you should probably use this function outside the .prototype and pass the object into it instead.

查看更多
素衣白纱
4楼-- · 2018-12-31 07:41

Or, easier yet - create a new object with the keys and values in the order you want then do look up against that object. We have had conflicts using the prototype codes above. You don't have to use the String function around the key, that is optional.

 newLookUpObj = {};
 $.each(oldLookUpObj,function(key,value){
        newLookUpObj[value] = String(key);
    });
查看更多
只若初见
5楼-- · 2018-12-31 07:45

This is a small extension to the Underscorejs method, and uses Lodash instead:

var getKeyByValue = function(searchValue) {
  return _.findKey(hash, function(hashValue) {
    return searchValue === hashValue;
  });
}

FindKey will search and return the first key which matches the value.
If you want the last match instead, use FindLastKey instead.

查看更多
伤终究还是伤i
6楼-- · 2018-12-31 07:45

I typically recommend lodash rather than underscore.

If you have it, use it.

If you don't, then you should consider using the lodash.invert npm package, which is pretty tiny.

Here's how you can test it using gulp:

1) Create a file called gulpfile.js with the following contents:

// Filename: gulpfile.js
var gulp = require('gulp');
var invert = require('lodash.invert');   
gulp.task('test-invert', function () {
  var hash = {
    foo: 1,
    bar: 2
  };
  var val = 1;
  var key = (invert(hash))[val];  // << Here's where we call invert!
  console.log('key for val(' + val + '):', key);
});

2) Install the lodash.invert package and gulp

$ npm i --save lodash.invert && npm install gulp

3) Test that it works:

$ gulp test-invert
[17:17:23] Using gulpfile ~/dev/npm/lodash-invert/gulpfile.js
[17:17:23] Starting 'test-invert'...
key for val(1): foo
[17:17:23] Finished 'test-invert' after 511 μs

References

https://www.npmjs.com/package/lodash.invert

https://lodash.com/

Differences between lodash and underscore

https://github.com/gulpjs/gulp

查看更多
荒废的爱情
7楼-- · 2018-12-31 07:46

Really straightforward.

const CryptoEnum = Object.freeze({
                    "Bitcoin": 0, "Ethereum": 1, 
                    "Filecoin": 2, "Monero": 3, 
                    "EOS": 4, "Cardano": 5, 
                    "NEO": 6, "Dash": 7, 
                    "Zcash": 8, "Decred": 9 
                  });

Object.entries(CryptoEnum)[0][0]
// output => "Bitcoin"
查看更多
登录 后发表回答