What steps should I follow to convert the cookie values into a 'key: value' array?

I need to create a comprehensive list of cookies along with their values, retrieve the values, and then store them in a different location

var cookieNames = ["Cookie1", "Cookie2", "Cookie3"];

function getCookie(cookieName) {
  let name = cookieName + "=";
  let decodedCookie = decodeURIComponent(document.cookie);
  let cookieArray = decodedCookie.split(';');
  let cookieValue = [];
  for(let i = 0; i < cookieArray.length; i++) {
    let cookie = cookieArray[i];
    while (cookie.charAt(0) == ' ') {
      cookie = cookie.substring(1);
    }
    if (cookie.indexOf(name) == 0) {
        cookieValue = [cookie.substring(name.length, cookie.length)];
 // Attempting here to generate a key-value pair list
       cookiesList +=[cookieName:cookie.value];
    }
  }
}

// Retrieve all cookie names from the list 
for (var key in cookieNames) {
 getCookie(cookieName);
}
// exportsTest~ Exporting the variable for testing purposes on Testim platform
exportsTest.cookiesList;

Once I have collected the cookie names and their respective values, I wish to set them at a separate location

function setCookie(cookieName, cookieValue, expiryDays) {
  const currentDate = new Date();
  currentDate.setTime(currentDate.getTime() + (expiryDays*24*60*60*1000));
  let expires = "expires="+ currentDate.toUTCString();
  document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";path=/";
}

// Setting all the cookies from the list 
for (var key in cookiesList) {
 setCookie(key, cookiesList[key], 120);
}

Is there something missing that could prevent this from functioning properly?

Answer №1

To get started, the first step is to set up your cookiesList variable:

const cookiesList = {};

Next, instead of using cookiesList +=[cname:c.value];, make the following adjustment:

cookiesList[cname] = c.value;

Please be aware:

The variable cookiesList must be defined properly and utilizing +=[cname:c.value]; (1) combines array and object syntax improperly, (2) adding elements or properties in this manner is not correct.

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

How can I change the transparency of a CSS background color using JavaScript?

I have a question about CSS: .class1 { background: #fff } Now, I need to achieve the following: .class2 { background: rgba(255,0,0,0.5) }; Is there a way to use JavaScript only to change the background property of .class1 and give it an opacity of 0.5? ...

Is it possible to retrieve the pixel color of a mesh by clicking on it in JavaScript?

On the current page, we have a mesh loaded with TreeJS and displayed in a canvas: https://i.sstatic.net/j8Ztj.png Is there a way to retrieve the color of the point where a click occurs? I attempted a method suggested in this thread: Getting the color val ...

Having difficulty getting a basic code to work: ajax method ($.post) with MySQL is not

I am facing an issue with this code not functioning properly. I want to display the result of a MySQL query without sending any data using my simple Ajax code. $('.myClass').on('click',function(){ $.post('resultAll.php'); ...

Combining objects in React: An exploration of array merging

I have an array of objects that look like this: [{ a=1, b=4, c=4, d=6}, { a=1, b=4, c=4, d=6}, …],[{ a=1, b=4, c=4, d=6}, { a=1, b=4, c=4, d=6}, …],[{ a=1, b=4, c=4, d=6}, { a=1, b=4, c=4, d=6}, …] My goal is to merge them into one unique array as ...

ESLint: The "react" plugin encountered a conflict

In my development environment, I have a React application within a single npm component package. This React app acts as a demonstration site that consumes the component package in addition to Storybook. local-component-package ├── .storybook ├─ ...

Encountering difficulty retrieving the value of a hidden input with jQuery's find method

When a user clicks on the delete icon, I want to retrieve the value of the hidden input inside the "delete" class. However, I am getting an undefined result. Can someone please guide me on where I might be going wrong? <table class="items-list"> ...

Enhancing a blog entry in Meteor.js

Recently, I embarked on a journey to learn Meteor.js in hopes of creating a newsfeed feature that allows me to add, edit, and delete content. As of now, I am facing challenges with the editing process. imports/api/news/methods.js Meteor.methods({ ...

Exploring AngularJS: the power of directives and the art of dependency

According to Angular documentation, the recommended way to add a dependency is by following these steps: Source //inject directives and services. var app = angular.module('fileUpload', ['ngFileUpload']); app.controller('MyCtrl&ap ...

The error message "THREE is not defined" indicates a problem

Hey there! I've been experimenting with running some three.js examples on my local machine. I ran into some security issues, so I set up a local server using Python. While the background image and text appear as expected, the animations are not workin ...

Algorithm to efficiently locate the final distinct element in sublinear time

Here's some context for you, but feel free to skip it: I spent the day recording audio for a project, one paragraph at a time. If I made a mistake in a paragraph, I would redo it until it was right before moving on to the next one. When I uploaded ev ...

How can React and react-router be used to direct users to a specific group of URLs

One scenario I have is when my users upload a group of photos, they need to add specific meta information for each one. After uploading the files, I want to direct them to the first photo's meta editor page. Then, when they click on the "next" button, ...

AngularJS event that is triggered once all scopes have been applied

In my AngularJS application, I am retrieving data from a REST service. Occasionally, the brackets {{}} used to access values from scope are initially rendered and then replaced by the actual values later on. My goal is to add an ng-switch to the main DIV o ...

Avoiding 0 being mistakenly interpreted as undefined while utilizing React Conditional Rendering

I have a React component with the following code in its render function: return ( <div> {rating.score && ( <div>do something</div> )} </div> ); The prop rating.score is of type PropTypes.number. Eve ...

I'm running into an issue where my API calls are being duplicated

Every time I refresh the page, the network preview displays a duplicate API call to (ipaddress)/(portnumber)/admin/user-group?page=1&page_size=10&query= twice. I've tried making changes to the useEffect() and handleSearch() functions without s ...

Guide to dynamically loading select options in AngularJS from a JSON file

Is there a way in AngularJS to populate select options from a JSON file? I am trying to figure out how to populate the dropdown with the following: todos.products.[DynamicProductName].attributes.Location Given that there are multiple product names under ...

Just discovered a background change triggered by the time, but unable to replicate it

I find it odd that everything works perfectly fine with document.body.style.background, yet I can't seem to change the style of this particular div. Here is the code snippet: var container = document.getElementById("container"); var updateTime = fu ...

When choosing from multiple dropdown menus, the selected option should be hidden from the other dropdowns

I'm currently working on a project that involves designing a web form incorporating 3 select boxes with multiple questions. The concept is such that, if I choose the 1st Question from the 1st select drop-down, it should not be available in the 2nd sel ...

What is the best way to assign an onClick event in React while using document.createElement()?

I am using document.createElement to create an <input>. How can I assign the onClick property in React? var input = document.createElement("input"); input.onClick = {setCount()}; //??? Here is the React code snippet: <input type="s ...

Struggling with AWS CognitoIdentityServiceProvider issues

Trying to access the adminGetUser function using the AWS CognitoIdentityServiceProvider is giving me some trouble. Although the initialization seems correct, I am encountering the following error message. [Nest] 43 - 03/29/2022, 9:18:43 AM ERROR [Except ...

How come jQuery each is failing to iterate through all JSON items from two functions simultaneously with $.when?

After checking with the Chrome Network inspector, it appears that the json returns from both ajax functions are downloading completely. However, there seems to be an issue with the jQuery each function as it is only going through the first three items of t ...