Generally, the value can be obtained through obj.key, but if I want to do the reverse, what should I do?
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.
key
value
for...inLoop object judgment and acquisition?
for...in
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
The output value is not unique. It can be obtained by value.
For reference, if you use lodash, you can directly use _.findKey
_.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
Can I recycle it? Take out $.each like this
The mapping from
key
tovalue
is one-way, andvalue
is not unique.So there is no problem in getting
value
fromkey
, but not vice versa.for...in
Loop object judgment and acquisition?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
The output value is not unique. It can be obtained by value.
For reference, if you use lodash, you can directly use
_.findKey
Can I recycle it? Take out $.each like this