title: Javascript: Quickly lookup value in object (like we can with properties)
body: <p>I have an object that has pairs of replacement values used for simple encoding / decoding (not for security, just for a convenience; too complicated to explain it all here). It's in the form</p>
  
  <pre><code>var obj = {x: y,
             x: y,
             ...
            };
  </code></pre>
  
  <p>where 'x' is the value when encoded and 'y' is the decoded value.</p>
  
  <p>Decoding is simple: I loop through the characters of the string, and look up the <code>charAt(i)</code> value in the object via brackets: <code>obj[ str.charAt(i) ]</code>. (I'm leaving out the check to see whether we need an uppercase or lowercase version (all key/values in the object are lowercase), but that's simple enough.)</p>
  
  <p>To encode, I of course have to look for the value in the object, rather than the property. Currently, I'm looping through the properties with a <code>for ... in ...</code> loop and checking the values against the <code>charAt(i)</code> value. My current code is:</p>
  
  <pre><code>var i, j,
      output = '',
      str = 'Hello World!',
      obj = {'s':'d',
             'm':'e',
             'e':'h',
             'x':'l',
             'z':'o',
             'i':'r',
             'a':'w',
             'o':'!',
             '-':' '};
  for (i = 0; i &lt; str.length; i++) {
      for (j in obj) {
          if (Object.prototype.hasOwnProperty.call(obj, j) &amp;&amp;
              Object.prototype.propertyIsEnumerable.call(obj, j)) {
              if (obj[j] === str.charAt(i)) {
                  output += j;
                  break;
              } else if (obj[j].toUpperCase() === str.charAt(i)) {
                  output += j.toUpperCase();
                  break;
              }
          }
      }
  }
  alert(output);
  </code></pre>
  
  <p>I innately feel like there should be a more efficient way of doing this. (Of course having a reversed object, {y: x}, is an option. But not a good one.) Is this the best way, or is there a better? In essence, I'd love to be able to do <code>var prop = obj[value]</code> just like I can do <code>var value = obj[prop]</code>.</p>