Create Array in Cookie with JavaScript

12/20/2021

Contents

In this article, you will learn how to create array in cookie with JavaScript.

Set array in cookie

Create a function that sets an array in a cookie.
Since the cookies can only handle text data, the array cannot be set as it is, but it can be set as a character string by converting the array to JSON.
You can convert an array to JSON with JSON.stringify().

Below is a function that uses JSON.stringify () to set an array in a cookie.

JavaScript

const setCookie = (name, json)=>{

  let cookieValue = '';
  let expire = '';
  let period = '';

  //Specify the cookie name and value
  cookieValue = name + '=' + JSON.stringify(json) + ';';

  //Specify the path to set the cookie
  cookieValue += 'path=/ ;';

  //Specify how long you want to keep cookie
  period = 30; //days to store
  expire = new Date();
  expire.setTime(expire.getTime() + 1000 * 3600 * 24 * period);
  expire.toUTCString();
  cookieValue += 'expires=' + expire + ';';

  //Set cookie
  document.cookie = cookieValue;
};

const json = {
  name: 'Plantpot',
  address: 'Tokyo',
  age: '99',
  email: 'xxx@example.com'
};
setCookie('user', json);
//name:user
//value:{"name":"Plantpot","address":"Tokyo","age":"99","email":"xxx@example.com"}

In the above, the object (associative array) format data is converted to JSON and set, but you can also set a normal array as shown below.

const array = [0, 1, 2, 3];
setCookie('numbers', array);

Get cookie in array

Get the array set in the cookie.
Since the cookie holds the data separated by semicolons, it divides each data into an array and then returns JSON to the array.
You can convert from JSON to an array with JSON.parse().

Below is a function to get a cookie using JSON.parse().

JavaScript

const getCookie = ()=>{
    
  let cookieValue = '';
  let cookieArray = new Array();
  let result = new Array();

  //Get cookie
  cookieValue = document.cookie;

  //Divide the cookie into an array and convert them to JSON
  if(cookieValue){
    cookieArray = cookieValue.split(';');
      
    cookieArray.forEach(data => {
      data = data.split('=');

      //data[0]: Cookie name
      //data[1]: Cookie value

      result[data[0]] = JSON.parse(data[1]);
    });
  }
  return result;
}

getCookie();

//user: {
//  name: "Plantpot",
//  address: "Tokyo",
//  age: "99",
//  email: "xxx@example.com"
//}