title: How can I create a two-way mapping in JavaScript, or some other way to swap out values?
body: <p>I currently have a need to temporarily swap out values in a JavaScript string, and therefore I will need to have a two-way map/hash thing.</p>
  
  <p>For example, let's say I want to change <code>\*</code> to <code>__asterisk__</code> (this is just an example, it's not what I'm actually trying to do). I'll have to be able to map <code>*</code> to <code>__asterisk__</code> (to swap out the value in the original string), but then I'll also have to be able to map <code>__asterisk__</code> back to <code>*</code> (to get the original string back).</p>
  
  <p>Here's some quick pseudo-ish code of the kind of thing that I'm looking for, so you can understand it better:</p>
  
  <pre><code>var myString = 'this is \* a test';
  
  // ???
  var twoWayMap = new TwoWayMap('*' &lt;---&gt; '__asterisk__', '%' &lt;---&gt; '__percent__', ...);
  
  var newString = myString.replace(/\\(.)/g, function(m, c) {
      return twoWayMap.getKey(c);
  });
  // newString is now 'this is __asterisk__ a test'
  
  // ... later in the code ...
  
  var oldString = newString.replace(/__([^_]+)__/g, function(m, c) {
      return twoWayMap.getValue(c);
  });
  // oldString is now 'this is * a test'
  </code></pre>
  
  <p>This is what I've thought about and tried so far:</p>
  
  <pre><code>var twoWayMap = {'*': '__asterisk__', '%': '__percent__', ...};
  
  // getKey would be like this:
  twoWayMap[c];
  // getValue would be like:
  var val; for (var x in twoWayMap) { if (twoWayMap[x] === c) { val = x; break } }
  </code></pre>
  
  <p>The obvious problem with this is that the way to get by value is much too complicated, and I don't want to have to write out the whole thing every single time I have to reverse lookup.</p>
  
  <p>I just wanted to know: Is there any way to solve this problem without resorting to looping through an object? If not, is there any way to make it easier or cleaner?</p>