0

I have cookie info stored in JSON format as follows:

var preferredAnimal = {
    "dog" : "true",
    "cat" : "false",
    "bird" : "true"
};

How would i just extract the info for one item? For example, i just want to check cookie, and do something if bird returns true.

Checking the cookie in devtools, the Name is preferredAnimal, and the value is {"dog":true,"cat":false,"bird":true}, so trying to identify the value gives me everything.

Any help appreciated

Pilgrimiv
  • 21
  • 3

2 Answers2

0

You can do the following:

if(preferredAnimal.bird == 'true')
{
   //do something
}
Timberman
  • 647
  • 8
  • 24
0

Assuming you used JSON.stringify to stringify your cookie, you can get it in its orignal form by using this function:

function getCookieAsJSON(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) 
     return JSON.parse(
          parts.pop()
         .split(';')
         .shift()
     );
}

Usage:

const cookie = getCookieAsJSONI('preferredAnimal') // preferredAnimal is the name of your cookie
console.log(cookie) // Returned cookie is an object just as your orignal object if you used JSON.stringify

Output:

 {
   dog: "true",
   cat: "false",
   bird:"true"
 }

Note, your values will be strings but you can cast them to the proper types easily.

Faraz
  • 433
  • 3
  • 7