search

Home  >  Q&A  >  body text

javascript - How does a Js object get the key value through the value value?

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

曾经蜡笔没有小新曾经蜡笔没有小新2733 days ago952

reply all(6)I'll reply

  • 大家讲道理

    大家讲道理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.

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-30 10:00:56

    for...inLoop object judgment and acquisition?

    reply
    0
  • 我想大声告诉你

    我想大声告诉你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

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-30 10:00:56

    The output value is not unique. It can be obtained by value.

    reply
    0
  • 三叔

    三叔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

    reply
    0
  • 怪我咯

    怪我咯2017-06-30 10:00:56

    Can I recycle it? Take out $.each like this

    reply
    0
  • Cancelreply