Convert the document.cookie string into an object?

Answered
suparman21 asked this question 21 days ago
suparman21 21 days ago

In my website, I have certain scenarios where I need to get a user's browser cookie data and do things with it.

How can I convert that string into an object that is easier to deal with?

For example, this cookie string:

"user=something;data=something"

Should be converted into an object like this:

{user: something, data: something}

I'm using JavaScript.

3 suggested answers
nick 13 days ago

You can use this function:

function convertCookiesToObject(cookieString) {
  let arrayOfCookies = cookieString.split(";")
  let resultObject = {}

  for (let i in arrayOfCookies) {
    const current = arrayOfCookies[i].split("=")
    resultObject[current[0]] = current[1]
  }

  return resultObject
}

You can put it to use like this:

convertCookiesToObject("user=something;data=something")

// returns { user: "something", data: "something"}
0 replies
yaboy01 13 days ago
cookieString.split(";").reduce((prev, current) => {
  const [name, ...value] = current.split("=")
  prev[name] = value.join("=")
  return prev
}, {})

This a short and sweet method that uses the reduce() method to convert the string into an object.

0 replies
itsbambi 13 days ago
let cookieString = "user=something;data=something;moredata=something"

let cookiesArray = cookieString.split(";")

let object = {}

for (let i=0; i < cookiesArray.length; i++) {
  const currentItem = cookiesArray[i].split("=")
  object[currentItem[0]] = currentItem[1]
}

console.log(object)
// returns { user: "something", data: "something", moredata: "something" }
0 replies
Answered