javascript - How does a Js object get the key value through the value value?
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-06-30 09:58:56
0
6
951

Generally, the value can be obtained through obj.key, but if I want to do the reverse, what should I do?

曾经蜡笔没有小新
曾经蜡笔没有小新

reply all(6)
大家讲道理

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.

过去多啦不再A梦

for...inLoop 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

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template