I have a line similar to document.cookie:
var str = 'foo=bar, baz=quux';
Converting it to an array is very simple:
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 more complicated.
str = JSON.parse('{' + str.replace('=', ':') + '}');
This creates an object that is invalid:
{foo: bar, baz: quux}
I need an object like this:
{'foo': 'bar', 'baz': 'quux'}
Note . I used single quotes in my examples, but when publishing code, if you use JSON.parse(), remember that double quotes are needed for single quotes.
Update
Thanks to everyone. Here is the function that I will use (for future use):
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;
}