title: Converting strings like document.cookie to objects
body: <p>I have a string similiar to <code>document.cookie</code>:</p>
  
  <pre><code>var str = 'foo=bar, baz=quux';
  </code></pre>
  
  <p>Converting it into an array is very easy:</p>
  
  <pre><code>str = str.split(', ');
  for (var i = 0; i &lt; str.length; i++) {
      str[i].split('=');
  }
  </code></pre>
  
  <p>It produces something like this:</p>
  
  <pre><code>[['foo', 'bar'], ['baz', 'quux']]
  </code></pre>
  
  <p>Converting to an object (which would be more appropriate in this case) is harder.</p>
  
  <pre><code>str = JSON.parse('{' + str.replace('=', ':') + '}');
  </code></pre>
  
  <p>This produces an object like this, which is invalid:</p>
  
  <pre><code>{foo: bar, baz: quux}
  </code></pre>
  
  <p>I want an object like this:</p>
  
  <pre><code>{'foo': 'bar', 'baz': 'quux'}
  </code></pre>
  
  <p><strong>Note</strong>: I've used single quotes in my examples, but when posting your code, if you're using <code>JSON.parse()</code>, keep in your mind that it requires double quotes instead of single.</p>
  
  <hr>
  
  <h2>Update</h2>
  
  <p>Thanks for everybody. Here's the function I'll use (for future reference):</p>
  
  <pre><code>function str_obj(str) {
      str = str.split(', ');
      var result = {};
      for (var i = 0; i &lt; str.length; i++) {
          var cur = str[i].split('=');
          result[cur[0]] = cur[1];
      }
      return result;
  }
  </code></pre>