Skip to content Skip to sidebar Skip to footer

Converting Strings Like Document.cookie To Objects

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++

Solution 1:

The shortest way

document.cookie.split('; ').reduce((prev, current) => {
    const [name, ...value] = current.split('=');
    prev[name] = value.join('=');
    return prev;
  }, {});

Solution 2:

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

Solution 3:

note : The document.cookie (question headline) is semicolon separated and not comma separated (question) ...

An alternative using reduce :

var str = 'foo=bar; baz=quux';
var obj = str.split(/[;] */).reduce(function(result, pairStr) {
  var arr = pairStr.split('=');
  if (arr.length === 2) { result[arr[0]] = arr[1]; }
  return result;
}, {});

Solution 4:

Given an array a containing your intermediate form:

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

then simply:

var obj = {};
for (var i = 0; i < a.length; ++i) {
   var tmp = a[i];
   obj[tmp[0]] = tmp[1];
}

Solution 5:

To convert it to an object, just do that from the beginning:

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

Then, if you want JSON out of it:

var jsonString = JSON.stringify(obj);

Post a Comment for "Converting Strings Like Document.cookie To Objects"