Generally, the value can be obtained through obj.key, but if I want to do the reverse, what should I do?
大家讲道理2017-06-30 10:00:56
The mapping from
key
to value
is one-way, and value
is not unique.
So there is no problem in getting value
from key
, but not vice versa.
我想大声告诉你2017-06-30 10:00:56
I have a stupid method
Traverse the object, determine whether the value of the current object is equal to the value to be checked, and if it matches the output key
三叔2017-06-30 10:00:56
For reference, if you use lodash, you can directly use _.findKey
var data = {
a: 1,
b: 'string',
c: {},
d: {a: 98, b: 'str'}
}
function findKey (value, compare = (a, b) => a === b) {
return Object.keys(data).find(k => compare(data[k], value))
}
var val = data.b
findKey(val) // b
// 自定义比较函数,比如结合 lodash 可以
findKey({a: 98, b: 'str'}, _.isEqual) // d