在JS中查找对象的特定值的键 [英] Find key for specific value on object in JS
问题描述
我有一个这样的对象,它是使用lodash的 _.zipObject()
函数生成的.所以我有2个数组,一个是位置,一个是数字.
I have an object as such that has been generated by using the lodash _.zipObject()
function. So I have 2 arrays, one of locations, one of numbers.
var locs = {'Aberdeen': 304, 'Aberystwith': 109, 'Belfast': 219, 'Birmingham': 24, 'Brighton': 147, …}
我需要根据输入值返回键.例如, function(304)
将返回'Aberdeen'
.
I need to return the key based on an input value. For example, function(304)
would return 'Aberdeen'
.
我已经尝试过 _.findkey(locs,304);
,但这只会返回未定义的内容.我尝试过的任何其他尝试总是返回undefined或-1.不太确定从这里去哪里.
I've tried _.findkey(locs, 304);
but this just returns undefined. Any other attempt I've tried always returns either undefined or -1. Not really sure where to go from here.
推荐答案
要查找键,请使用带有 _.findKey()
:
To find the key use a predicate function with _.findKey()
:
var locs = {'Aberdeen': 304, 'Aberystwith': 109, 'Belfast': 219, 'Birmingham': 24, 'Brighton': 147 };
var key = _.findKey(locs, function(v) {
return v === 304;
});
console.log(key);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
您可以通过使用所请求的值使用 _.eq()
来创建谓词:
You can create the predicate by currying _.eq()
with the requested value:
var locs = {'Aberdeen': 304, 'Aberystwith': 109, 'Belfast': 219, 'Birmingham': 24, 'Brighton': 147 };
var key = _.findKey(locs, _.curry(_.eq, 304));
console.log(key);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
这篇关于在JS中查找对象的特定值的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!