Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
11
rated 0 times [  18] [ 7]  / answers: 1 / hits: 31740  / 14 Years ago, fri, february 18, 2011, 12:00:00

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;
}

More From » arrays

 Answers
28

Why exactly do you need JSON.parse in here? Modifying your arrays example




let str = foo=bar; baz=quux;

str = str.split('; ');
const result = {};
for (let i in str) {
const cur = str[i].split('=');
result[cur[0]] = cur[1];
}


console.log(result);




[#93674] Thursday, February 17, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
caylasarinag

Total Points: 194
Total Questions: 107
Total Answers: 105

Location: Benin
Member since Sun, Jan 29, 2023
1 Year ago
;