What is the method for utilizing document.cookie to save and access data in an array structure?

Currently, I have successfully implemented methods to store and retrieve values in cookies:

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
};

as well as

function getCookie() {
    var name = "name=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}; 

Now, my next challenge is to handle storing/retrieving arrays in a similar manner. It seems logical to convert the array into a single string before storage and then parse it back when retrieving, but what would be the most efficient way to accomplish this?

Answer №1

My suggestion would be to utilize JSON. The initial step involves transforming the array into a JSON string:

let myArray = ["apple", "banana", "orange"];
let jsonString = JSON.stringify(myArray);

Next, store the JSON string as the value of the cookie.

setCookie("myArray", jsonString, expirationDays);

Then, when you need to retrieve the JSON string from the cookie in the future, convert it back into an array.

let storedJsonString = getCookie("myArray");
let newArray = JSON.parse(storedJsonString);

Answer №2

Suppose you are looking to manage multiple cookies for storage or retrieval. Your current function "getCookies()" almost accomplishes this:

function getCookies() {
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
return ca.map(function(c){
    while (c.charAt(0) == ' ') {
        c = c.substring(1);
    }
        return c.split("=");
    }
});
}; 

The adjustment needed is to retrieve all cookies instead of just the first one and eliminate name detection.

console.log(getCookies());

To set cookies:

function setCookies(Cookies, exp){
 Cookies.forEach(function(el){setCookie(el[0], el[1], exp);});
}

setCookies([
  ["name", "value"]
 ]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Do not fulfill the promise until all the images have finished loading

Below is the intended process: Iterate through a collection of img tags Retrieve each tag's src URL Convert it to a base64 encoded string using an HTML 5 canvas Once all images have been converted, resolve the promise and call the callback function ...

Is there a method available for us to successfully deliver an email to the user who has been registered?

I am currently working on the registration page for my React app. One of the requirements is to send a confirmation email to the user's email address once they have registered. The user's account will only be confirmed once they click on the veri ...

evaluate individual methods within a stateless component with unit testing

I am working with a stateless component in React that I need to test. const Clock = () => { const formatSeconds = (totalSeconds) => { const seconds = totalSeconds % 60, minutes = Math.floor(totalSeconds / 60) return `${m ...

There was an issue with d3 version 4: the function this.setAttribute() was not

I am attempting to update the provided example to be compatible with d3 version 4 http://bl.ocks.org/ameyms/9184728 Most of the code has been successfully converted, but I am encountering difficulties with the following function: this.el.transition().del ...

Iterate through the session array variable

Developing a shopping cart functionality that stores selected items in a session array until the checkout process. Each item is stored as follows: $_SESSION['cart']['items']['item number'] -> containing fields such as quant ...

What techniques do Node libraries employ to achieve asynchronous execution in a professional manner?

After researching how Node Bcrypt accomplishes asynchronous execution with the following code: bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) { // Store hash in your password DB. }); I am curious about how they manage to perform com ...

Tips for resolving an issue with mongoose Model.create becoming unresponsive indefinitely

I'm having trouble understanding why my mongoose Model.create operation isn't completing successfully. The same connection is working well with other controller functions. vscode postman I am attempting to create a new document, but my code s ...

Exploring the properties and methods of a node.js module object through iteration

Looking to compile a comprehensive list of all the Properties and Methods associated with the os Node.js module. One possible method is: var os = require('os'); Object.keys(os); Object.getOwnPropertyNames(os); Given that the os module is an Obj ...

The image displayed by the @vercel/og API route is not appearing correctly

I am currently facing an issue with my Next.js app hosted on Vercel Edge while trying to set up the Vercel/og package. You can find more information about it here: https://vercel.com/docs/concepts/functions/edge-functions/og-image-generation Upon loading ...

Using JSON.stringify to format data and making an asynchronous $http request

I am working with a JavaScript string that looks like this: user_fav = "21,16"; I need to process this string through a function so that it becomes a JSON array with an id key, like this: {"id":21},{"id":16} This JSON array is then used in an $http req ...

What is the best way to utilize Angular to conceal an image until it is fully loaded?

I am currently utilizing angularjs to dynamically generate images. My goal is to hide or show a placeholder for each <img> element until it fully loads. Is it possible to achieve this directly in my html, or should I handle it through the controlle ...

What is the best way to differentiate and analyze new AJAX output from previous data using div elements?

Embarking on a project to develop a high/low game using JavaScript, I encountered a perplexing issue where the displayed numbers seemed to be out of sync with the variables stored. This discrepancy left me scratching my head as I struggled to get them to a ...

Obtaining information through numerous JSONP requests

I am intrigued by the process of retrieving data using multiple jsonp requests. Is it practical? Currently, the code fragment below is what I am using in my CRA (pseudocode). import * as fetch from 'fetch-jsonp'; import * as BlueBird from ' ...

Learn how to retrieve specific user information from a JSON file by implementing a button click feature within a custom directory using Angular.js

I am just starting to learn angular.js and I'm trying to figure out how to retrieve JSON data from a custom directory. My goal is to display the information of a specific user when a particular button is clicked, but so far I haven't been success ...

Inject a DOM event into a personalized form validator within an Angular application

I'm currently working on validating a form using the reactive approach. I've implemented a file input to allow users to upload files, with custom validation conditions in place. However, I'm encountering an issue where the validator only rec ...

Failing to send contact information using JSON in PHP

I attempted to transmit JSON data to PHP for email processing, but encountered an issue where the process veered into the 'else' condition during debugging. Here is the code snippet: HTML <form id="cbp-mc-form" class="cbp-mc-form" method="po ...

Modify all content located between two specified text or strings

My goal is to replace the content between [lorem] and [/lorem]. For example: [lorem]Here goes some text[/lorem] should be transformed into This is inside a lorem block I was able to achieve this with [[Here goes some text]], using var block = $(&apos ...

Updating the DOM after scrolling using jQuery

jQuery hover functionality is not working correctly after scrolling. $(document).ready(function() { $('img').hover(function(){ alert('hello'); },function(){ alert('hello not'); }); }); When hoveri ...

How can I transform any object (such as an array) into JSON format and retrieve it as a string? Specifically in the context of Android

Is there a method to convert any type of object, like an array, into JSON and retrieve it in string format? Here's an example: public String jsonEncode(Object obj) { return jsonString; } ...

The default prevention of a generated link by React Router is a distinctive feature

After implementing React Router in my code, I encountered an issue where all the links generated by <Link> or even <a> tags were not working correctly. When hovering over these links, the URL appeared as expected, but clicking on them did not c ...