我有一个非常简单的JavaScript对象,我将其用作关联数组。是否有一个简单的函数允许我获取值的键,或者我必须迭代对象并手动找到它?
当前回答
lodash way https://lodash.com/docs#findKey
Var用户= { 'barney':{'年龄':36,'活跃':true}, 'fred': {'age': 40, 'active': false}, '鹅卵石':{'年龄':1,'活动':true} }; _。findKey(users, {'age': 1, 'active': true}); //→'鹅卵石'
其他回答
来到这里(2022年),寻找OP问题的近似变体。变化:
如何根据一个值找到一个对象键,其中键可以保存值的集合?
对于这个用例,从equal(===)切换到.includes():
const foo = ['a', 'b','c'];
const bar = ['x', 'y', 'z'];
const bat = [2, 5, 'z'];
const obj = {foo: foo, bar: bar, bat: bat};
const findMe = (v) => {
return Object.keys(obj).filter((k) => obj[k].includes(v))
}
findMe('y') // ['bar']
findMe('z') // ['bar', 'bat']
最短一行
let key = Object.keys(obj).find(k=>obj[k]===value);
返回值为:
let keys = Object.keys(obj).filter(k=>obj[k]===value);
如果value为数组或对象:
let keys = Object.keys(obj).filter(k=>JSON.stringify(obj[k])===JSON.stringify(value));
如果你正在使用下划线或Lodash库,你可以使用_。findKey功能:
var users = {
'barney': { 'age': 36, 'active': true },
'fred': { 'age': 40, 'active': false },
'pebbles': { 'age': 1, 'active': true }
};
_.findKey(users, function(o) { return o.age < 40; });
// => 'barney' (iteration order is not guaranteed)
// The `_.matches` iteratee shorthand.
_.findKey(users, { 'age': 1, 'active': true });
// => 'pebbles'
// The `_.matchesProperty` iteratee shorthand.
_.findKey(users, ['active', false]);
// => 'fred'
// The `_.property` iteratee shorthand.
_.findKey(users, 'active');
// => 'barney'
我们可以使用简单的函数来获取传递的值
const getKeyByValue = (object, value) => Object.keys(object).find(key => object[key] === value)
function extractKeyValue(obj, value) {
return Object.keys(obj)[Object.values(obj).indexOf(value)];
}
用于闭包编译器提取编译后未知的键名
更性感的版本,但使用未来对象。项功能
function objectKeyByValue (obj, val) {
return Object.entries(obj).find(i => i[1] === val);
}