Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting strings like document.cookie to objects

Tags:

I have a string similiar to document.cookie:

var str = 'foo=bar, baz=quux';

Converting it into an array is very easy:

str = str.split(', ');
for (var i = 0; i < str.length; i++) {
    str[i].split('=');
}

It produces something like this:

[['foo', 'bar'], ['baz', 'quux']]

Converting to an object (which would be more appropriate in this case) is harder.

str = JSON.parse('{' + str.replace('=', ':') + '}');

This produces an object like this, which is invalid:

{foo: bar, baz: quux}

I want an object like this:

{'foo': 'bar', 'baz': 'quux'}

Note: I've used single quotes in my examples, but when posting your code, if you're using JSON.parse(), keep in your mind that it requires double quotes instead of single.


Update

Thanks for everybody. Here's the function I'll use (for future reference):

function str_obj(str) {
    str = str.split(', ');
    var result = {};
    for (var i = 0; i < str.length; i++) {
        var cur = str[i].split('=');
        result[cur[0]] = cur[1];
    }
    return result;
}