What is the proper method for assigning a value to a variable within a JSON

While utilizing the js.cookie.js library available on Github, I encountered a challenge when attempting to set a JSON cookie. According to the documentation for js.cookie.js, in order to set a JSON cookie, the following syntax should be used:

Cookies.set('name', { foo: 'bar' });

Subsequently, if you retrieve the cookie data using Cookies.getJSON('name');, the output will resemble the following:

{ foo: 'bar' }

Now, my inquiry is how to dynamically set the value of foo from a JavaScript variable. During my attempt, the approach below did not yield the desired outcome:

var myVar = 'foo';
Cookies.set('name', { myVar: 'bar' });

Ultimately, the result was { myVar: 'bar' } instead of { foo: 'bar' }.

To view my test on JSFIDDLE.COM, please visit: https://jsfiddle.net/nz2ur613/

Answer №1

document.onload = Execute();
   function Execute() {
   var myVariable = 'foo';
   var myObject = {} ;
   myObject[myVariable] = 'bar';
   Cookies.set('name', myObject);
   alert(Cookies.get('name'));
 }

I have created an object and stored it in a cookie.

Give this code a try, it should work

Demo : https://jsfiddle.net/snuny9om/

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

What is the best way to retrieve the value of a textbox in AngularJS?

Trying my hand at creating a basic web page using angular. I've got 2 textboxes and 2 buttons - one to set a predefined value in a textbox, and the other to add some text. Here's the code snippet: <!DOCTYPE html> <html lang="en" ng-app ...

Combining multiple JSON objects into a single array in AngularJS

Currently, I am facing a challenge in merging two API calls. The first call involves fetching data by filtering the account_id on the backend, while the second call retrieves data based on the test_id. Let's start with the JSON response for /api/test ...

I have successfully integrated my custom external JavaScript code with React Router, and everything is working

Assistance Needed! I am working on a project that consists of 4 pages, one of which is the About page. I am using react-router to manage the paths and contents between these pages through their respective links. import React from 'react'; impo ...

The POST method in Node JS request-promises does not properly handle string inputs

When I am trying to establish a connection between my node.js module and another server, I utilize the 'request-promise' library. My implementation for posting data looks like this: rp.({ method: 'POST', headers:{ 'Conte ...

Setting up the permanent class path for Nodejs in Linux Mint

Recently, I attempted to install Nodejs Version 6.9.4 on my Linux Mint system using the following steps: $ cd /tmp $ wget http://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.gz $ tar xvfz node-v6.3.1-linux-x64.tar.gz $ mkdir -p /usr/local/nodejs $ mv ...

Issue in JavaScript / D3.js: When button is clicked, data fails to update and instead new positions are plotted

When the user clicks a button, both the red woman (unvaccinated) and the blue woman (vaccinated) should be updated to reflect the new value. At present, when the button is clicked, the red woman updates correctly but the blue woman is recreated in the loca ...

Customize and Enhance Code for Website Integration

My code is fetching a script from an external website. var url = "//example.com/script-url.js"; $.ajax({ url: url, dataType: 'jsonp' }); Although it functions properly, the script retrieved is created by a different website. I need to make ...

What are some clever ways to handle the transition of the display property?

While transitions for the display property may not work, I am exploring alternatives. I attempted using the visibility property but it didn't quite fit my needs. In my current setup, different text is displayed when hovering over an anchor tag by sett ...

Using Vue's transition mode alongside v-for and v-if does not appear to function correctly

When using Vue with Vuetify, I am trying to dynamically change v-cards with the help of animate.css. However, I have run into an issue. The out-in mode is not working in this scenario as both fade-in and fade-out animations occur simultaneously. Is there a ...

"Looking to access your Express app in a VM from the internet? Here's how

I have an express app running on a Node.js server hosted on Azure Linux VM, and I am looking to access this website from my personal computer. const express = require('express'); const app = express(); app.listen(3000, () => { console.lo ...

Utilizing SASS, JavaScript, and HTML for seamless development with Browser Sync for live syncing and

I've been on a quest to find a solution that covers the following requirements: Convert SASS to CSS Post-process CSS Minify CSS Move it to a different location Bundle all Javascript into one file Create compatibility for older browsers Tre ...

Having trouble with looping through subarrays using Javascript and JSON

I am attempting to iterate through a JSON object using Javascript (jQuery). Within the main JSON object, each object in the array contains embedded arrays of tags. My goal is to loop through all the files in the main object and simultaneously iterate thro ...

Tips for resolving the issue of the symbol ' displaying as &#39 in an Angular 2 application

I am currently working on an Angular application that makes API calls when a name displayed in a grid table is clicked. However, I have encountered an issue where names containing an apostrophe are being displayed incorrectly as &#39 instead. I managed ...

Tips for sending a reference to a JavaScript function

While constructing a table with DataTables and utilizing AJAX as its data source, I am encountering an issue with passing a function into the AJAX parameters. The $.post() function from regular JQuery seems to always send the value of my variable when the ...

Display a portion of the existing URL as a clickable link on the webpage using JavaScript or PHP

If I have a website with the URL and I would like to showcase the image at https://example.com/image.jpg on my site (), what can I do? I attempted the following approach, but it only displays the URL of the image. <p id="image"></p> <scri ...

What is preventing me from retrieving these JSON values?

One of the functionalities on my website involves making an AJAX call to retrieve a member's profile information for editing purposes. The code snippet responsible for this operation is shown below: function loadProfileData() { var ...

Executing Laravel Ajax Requests on the whole website

I have been encountering an issue with my Ajax post call in my application. The call is supposed to update the Navigation throughout the entire site, but it seems to be working on some pages and not others. I am looking for a way to fix this and make it mo ...

sending information to PHP through AJAX dynamically

I implemented a registration form that utilizes function user_reg(user_name,user_email,user_pswd) { var serverpath=window.location; alert(serverpath); var dataString = 'name='+ user_name + '&email=' + user_email + '&psw ...

What are the steps to connect to, fetch, save, and remove files from a remote file server using Node.js?

Currently working on a project in node.js that requires saving an uploaded file from a client onto a remote file server for later retrieval. While I'm familiar with accessing and storing files on the local file system using 'fs', I am unsure ...

Prevent form submission when email is missing

function validateEmail(){ var TCode = document.getElementById('email').value; if(TCode.length==0) { email_info.innerHTML="This field is required"; return false; } email_info.innerHTML=" "; ...