Items added to localStorage will not be able to store objects that have keys with array values

There seems to be an issue with how localStorage.setItem stores object values when the object contains keys with array values.

var obj = data : { cachedat : ['1' , 2 , 3] };
localStorage.setItem('data' , JSON.stringify(obj) );

However,

 var arr = JSON.parse(localStorage.getItem('data')) ; 
return like arr = data " { cachedat : []};

Answer №1

Remember that your script needs to look like this:

let object = {'info' : { 'cache' : ['x' , 7 , 8] }}
localStorage.setItem('info' , JSON.stringify(object) );

Answer №2

Be sure to provide an object when using JSON.stringify:

let exampleObj = {content: { cache : ['apple' , 'banana' , 'orange'] }};
localStorage.setItem('storageItem' , JSON.stringify(exampleObj) );

let parsedArray = JSON.parse(localStorage.getItem('storageItem')) ; 

Answer №3

Here is an example of how you can achieve this:

let myObject = {
  information: { numbers:[7 , 8 , 9] }
};

localStorage.setItem('info' , JSON.stringify(myObject));

let result = JSON.parse(localStorage.getItem('info')); 
console.log(result);

Result of the code snippet above:

{
  information: {
    numbers: [7, 8, 9]
  }
}

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

Switching the visibility of rows in a table

Imagine this as my example table: <table> <tr> <td>a</td> <td>one</td> <td>two</td> </tr> <tr> <td>b</td> <td>three</td> <td>four</t ...

Leveraging the power of axios.all for dynamic operations

Is there a way to efficiently reuse the same Vue-component for both editing and creating new users? While working with vue-router, I have implemented a beforeRouteEnter method to fetch data via API. Depending on whether an ID is set in the URL parameter, ...

The Javascript function may not function correctly after being called multiple times

I am currently working on an app that will randomly generate a question from two sets of data: country and questions. The user will then input their answer in a text box, which will be checked for correctness. While the app runs smoothly most of the time, ...

Exploring strategies for connecting React components with two distinct sources of information

Greetings! I am looking to display information about schools and also include images of the schools or programs. I have separate URLs for images and information stored in different states, with images saved on S3 and information in PostgreSQL. This has le ...

Leveraging the clearTimeout method to handle multiple occurrences of setTimeout

I have developed a unique twist on the classic Tic Tac Toe game called 'advanced' Tic Tac Toe. In this version, each move made by a player disappears after 10 seconds, returning the square to its original blank state. Everything works smoothly in ...

What is the solution for handling the error 'Mismatch between argument types and parameters' in TypeScript while using React Navigation?

Encountered an issue while trying to utilize Typescript in ReactNavigation and received an error from my IDE (WebStorm). Here is my Navigator: export type RootStackParamList = { AppStack: undefined; AuthStack: undefined; }; const RootStack = crea ...

Nest is unable to resolve the dependencies of the ItemsService. Ensure that the required argument at index [0] is present within the AppModule context

After following the Nest JS Crash tutorial from a Youtube Link, I encountered an error when importing an interface in the service. Nest seems unable to resolve dependencies of the ItemsService. It's important to ensure that the argument at index [0 ...

Retrieve resources from a pre-built npm package on-the-fly

Question regarding the creation of npm packages and the ability to dynamically request resources from one package in another. Imagine I have a collection of images in package A, along with JavaScript logic to fetch them: // Inside package B import Compone ...

Tips on extracting value from a pending promise in a mongoose model when using model.findOne()

I am facing an issue: I am unable to resolve a promise when needed. The queries are executed correctly with this code snippet. I am using NestJs for this project and need it to return a user object. Here is what I have tried so far: private async findUserB ...

Ag-Grid is failing to display MenuTabs

I need help getting the columns menu tab to appear in Ag-Grid. It should be a simple task. I want both the general and columns tabs, similar to the demo shown here Currently, when I specify both tabs, only the general tab is displayed. If I specify just t ...

Tips for locating a specific value within an array using ReactJS

I have a set of dates provided by the back-end that I need to work with in order to perform a specific check. If the list contains dates from the month of March, I should display the events for March, and the same for April, and so on. My task involves se ...

Interactive Navigation Bar in JavaScript

Is there a way to create a horizontal menu with an arrow that follows the mouse cursor? I saw this effect on a website (http://cartubank.ge) and I'm curious if anyone has the source code for it? Your help would be greatly appreciated. ...

Changing the names of the remaining variables while object destructuring in TypeScript

UPDATE: I have created an issue regarding this topic on github: https://github.com/Microsoft/TypeScript/issues/21265 It appears that the syntax { ...other: xother } is not valid in JavaScript or TypeScript, and should not compile. Initial Query: C ...

Place the file in the designated area for styling purposes

Within the pluploader, a file drop zone exists with the identifier dropFilesHere; var uploader = new plupload.Uploader({ drop_element : "dropFilesHere", /*...*/ }); If a user hovers a file over the drop zone, I want to customize it* ...

Determine in a JSON array and add to an array object if the key is not found

I've got a JSON array like this: 0: {Id: "1", name: "Adam", Address: "123", userId: "i98"} 1: {Id: "2", name: "John", Address: "456"} The second object in the array doesn't have a userId key. How can I iterate through the array and add the ...

Stop javascript function from automatically invoking itself

I am new to php and javascript and currently working on using a session variable to keep track of a counter. I want the counter to increment on the next button click and decrement on the previous button click. The issue I'm facing is with the JavaScri ...

Looking to preserve the "ALL" selection in a JavaScript-CSS filter?

On the front page, there are approximately 16 posts displayed along with a filter featuring 4 drop-down menus showcasing post categories. I have assigned category names as classes to each post div and am currently using javascript to hide them. The code s ...

Rather than overwriting it, append a new value to the localstorage

I am trying to insert the value of newUsername into the localStorage setUsernamesArray. However, my current code overwrites the existing value instead of adding to it. Code $('#signUpButton').click(function() { var newUsername = $('#userna ...

How to detect the Back Button or Forward Button events in a single-page application

Currently, I am developing a single-page application that utilizes ASP.NET MVC, Backbone.js, and JQuery. My task involves capturing the browser's back and forward button events for breadcrumb implementation. I previously attempted to use the hashchan ...

Making a POST request to Keycloak from Postman successfully retrieves the access token, however, using AXIOS in a NodeJs environment does not yield

I'm having trouble fetching the access token from Keycloak using Axios in NodeJs. When I make the call, it fails with a 'connect ECONNREFUSED ::1:8080' error. However, the same call is successful when made through Postman. I can't seem ...