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:53

As said, iteration is needed. For instance, in modern browser you could have:

var key = Object.keys(obj).filter(function(key) {return obj[key] === value})[0];

Where value contains the value you're looking for. Said that, I would probably use a loop.

Otherwise you could use a proper "hashmap" object - there are several implementation in JS around - or implement by your own.

UPDATE 2018

Six years passed, but I still get some vote here, so I feel like a more modern solution – for modern browser/environment – should be mentioned in the answer itself and not just in the comments:

const key = Object.keys(obj).find(key => obj[key] === value);

Of course it can be also a function:

const getKeyByValue = (obj, value) => 
        Object.keys(obj).find(key => obj[key] === value);
查看更多
心情的温度
3楼-- · 2018-12-31 07:54

If you have (or want) a dependency on underscore.js, you can use the findKey function. Eg,

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

es6

_.findKey(test, (val) => val === 42);

es5

_.findKey(test, function(val) {
    return val === 42;
});
查看更多
倾城一夜雪
4楼-- · 2018-12-31 07:56

Keep it simple!

You don't need to filter the object through sophisticated methods or libs, Javascript has a built in function called Object.values.

Example:

let myObj = {jhon: {age: 20, job: 'Developer'}, marie: {age: 20, job: 
'Developer'}};

function giveMeTheObjectData(object, property) {
   return Object.values(object[property]);
}

giveMeTheObjectData(myObj, 'marie'); // => returns marie: {}

This will return the object property data.

References

https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/values

查看更多
何处买醉
5楼-- · 2018-12-31 07:56

Here's a Lodash solution to this that works for flat key => value object, rather than a nested object. The accepted answer's suggestion to use _.findKey works for objects with nested objects, but it doesn't work in this common circumstance.

This approach inverts the object, swapping keys for values, and then finds the key by looking up the value on the new (inverted) object. If the key isn't found then false is returned, which I prefer over undefined, but you could easily swap this out in the third parameter of the _.get method in getKey().

// Get an object's key by value
var getKey = function( obj, value ) {
	var inverse = _.invert( obj );
	return _.get( inverse, value, false );
};

// US states used as an example
var states = {
	"AL": "Alabama",
	"AK": "Alaska",
	"AS": "American Samoa",
	"AZ": "Arizona",
	"AR": "Arkansas",
	"CA": "California",
	"CO": "Colorado",
	"CT": "Connecticut",
	"DE": "Delaware",
	"DC": "District Of Columbia",
	"FM": "Federated States Of Micronesia",
	"FL": "Florida",
	"GA": "Georgia",
	"GU": "Guam",
	"HI": "Hawaii",
	"ID": "Idaho",
	"IL": "Illinois",
	"IN": "Indiana",
	"IA": "Iowa",
	"KS": "Kansas",
	"KY": "Kentucky",
	"LA": "Louisiana",
	"ME": "Maine",
	"MH": "Marshall Islands",
	"MD": "Maryland",
	"MA": "Massachusetts",
	"MI": "Michigan",
	"MN": "Minnesota",
	"MS": "Mississippi",
	"MO": "Missouri",
	"MT": "Montana",
	"NE": "Nebraska",
	"NV": "Nevada",
	"NH": "New Hampshire",
	"NJ": "New Jersey",
	"NM": "New Mexico",
	"NY": "New York",
	"NC": "North Carolina",
	"ND": "North Dakota",
	"MP": "Northern Mariana Islands",
	"OH": "Ohio",
	"OK": "Oklahoma",
	"OR": "Oregon",
	"PW": "Palau",
	"PA": "Pennsylvania",
	"PR": "Puerto Rico",
	"RI": "Rhode Island",
	"SC": "South Carolina",
	"SD": "South Dakota",
	"TN": "Tennessee",
	"TX": "Texas",
	"UT": "Utah",
	"VT": "Vermont",
	"VI": "Virgin Islands",
	"VA": "Virginia",
	"WA": "Washington",
	"WV": "West Virginia",
	"WI": "Wisconsin",
	"WY": "Wyoming"
};

console.log( 'The key for "Massachusetts" is "' + getKey( states, 'Massachusetts' ) + '"' );
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

查看更多
姐姐魅力值爆表
6楼-- · 2018-12-31 07:57
function extractKeyValue(obj, value) {
    return Object.keys(obj)[Object.values(obj).indexOf(value)];
}

Made for closure compiler to extract key name which will be unknown after compilation

More sexy version but using future Object.entries function

function objectKeyByValue (obj, val) {
  return Object.entries(obj).find(i => i[1] === val);
}
查看更多
登录 后发表回答