In JavaScript, a single cookie can only store one name-value pair. To store multiple name-value pairs, there are two common approaches:
1. Serialize the Custom Object as a JSON String: This involves converting an object into a JSON string, storing it in a cookie, and then parsing it back into an object when needed.
2. Use Separate Cookies for Each Name-Value Pair: This involves creating a separate cookie for each key-value pair you need to store.
This approach allows you to store complex data structures in a single cookie. Here's how you can do it:
This approach allows you to store complex data structures in a single cookie. Here's how you can do it:
<script>
// Creating an object with multiple name-value pairs
let userPreferences = {
theme: "dark",
fontSize: "16px",
language: "en"
};
// Serialize the object to a JSON string
let jsonString = JSON.stringify(userPreferences);
// Set the cookie
document.cookie = `userPreferences=${jsonString};path=/;expires=Fri, 31 Dec 2024 23:59:59 GMT`;
// Function to get the cookie value by name
function getCookie(name) {
let value = `; ${document.cookie}`;
let parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
// Get and parse the cookie value
let storedPreferences = getCookie('userPreferences');
let parsedPreferences = JSON.parse(storedPreferences);
document.write(parsedPreferences);
</script>
This approach involves creating and managing multiple cookies, each storing a single key-value pair.
<script>
// Set multiple cookies
document.cookie = `theme=dark;path=/;expires=Fri, 31 Dec 2024 23:59:59 GMT`;
document.cookie = `fontSize=16px;path=/;expires=Fri, 31 Dec 2024 23:59:59 GMT`;
document.cookie = `language=en;path=/;expires=Fri, 31 Dec 2024 23:59:59 GMT`;
// Function to get the cookie value by name
function getCookie(name) {
let value = `; ${document.cookie}`;
let parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
// Get and log each cookie value
let theme = getCookie('theme');
let fontSize = getCookie('fontSize');
let language = getCookie('language');
document.write(theme); // dark
document.write(fontSize); // 16px
document.write(language); // en
</script>