Is it possible to alter local storage settings?

I've integrated simplecartjs into my online store to manage product data. The data is stored in local storage and currently looks like this:

{"SCI-1":{"quantity":1,"id":"SCI-1","price":20,"name":"Matt Black Tape","size":"Empty"},"SCI-3":{"quantity":1,"id":"SCI-3","price":19,"name":"Mohawk Soundproofing Mat 48 x 39cm"},"SCI-5":{"quantity":2,"id":"SCI-5","price":8,"name":"Car Speaker Air Freshener","color":"Green Tea"},"SCI-7":{"quantity":1,"id":"SCI-7","price":50,"name":"Installation Package"},"SCI-9":{"quantity":1,"id":"SCI-9","price":30,"name":"Quartz Films","color":"Yellow","size":"50cm x 30cm"},"SCI-11":{"quantity":1,"id":"SCI-11","price":30,"name":"Quartz Films","color":"True Blue","size":"50cm x 30cm"}}

Now, I want to include the following line before it closes.

"SCI-12":{"quantity":1,"id":"SCI-12","price":5,"name":"Shipping Costs"}

However, the number of products may vary based on the user, so SCI-12 should adjust accordingly with the items.

EDIT It doesn't have to be SCI-1, any identifier will work as long as it comes after the items.

EDIT2 I'm attempting the following code... But it's not working as expected.

$("#matkahuolto").click(function(){
    var value_object = '"Shipping Costs":{"quantity":1,"id":"Shipping Costs","price":5,"name":"Shipping Costs"}';
    var json_object = JSON.parse(localStorage.your_json); // convert string to object

    json_object["simpleCart_items"] = value_object; // add value

    localStorage.your_json = JSON.stringify(json_object);  // store it again.

    });

    $("#posti").click(function(){
    var json_object = JSON.parse(localStorage.your_json); // convert string to object

    json_object["simpleCart_items"] = value_object; // add value

    localStorage.your_json = JSON.stringify(json_object);  // store it again.

    });

EDIT3 A snapshot of the local storage.

Answer №1

Understanding how items are stored in localStorage is crucial. It functions like a hashmap/dictionary where items are saved in key-value pairs.

For instance, to store a string in localStorage, you would use:

localStorage["myKey"] = "some value";

To retrieve the value later, you simply reverse the process:

var myValue = localStorage["myKey"];

It's important to note that only strings can be stored in localStorage. If you wish to store an object, you must first convert it into a string format, usually using JSON. The JSON.stringify method converts an object to JSON, and JSON.parse does the opposite.

Here's an example of converting an object to JSON:

var someObject = {id: 1, name: 'Test'};

var jsonSomeObject = JSON.stringify(someObject);
// jsonSomeObject now looks like "{"id":1,"name":"test"}"

To read an object from JSON:

someObject = JSON.parse(jsonSomeObject);

In your case, assuming your object contains the necessary data, you can simply stringify your object and add it to localStorage with a specific key:

var jsonData = JSON.stringify({"SCI-12":{"quantity":1,"id":"SCI-12","price":5,"name":"Toimituskulut"}});

localStorage["aKey"] = jsonData;

When you need to access this data later:

var mySCI = JSON.parse(localStorage["aKey"])

If you want to update a specific entry in localStorage, read it in, make changes, and then overwrite it:

var mySCI = JSON.parse(localStorage["aKey"]);
mySCI.SCI-12.quantity = 2;
localStorage["aKey"] = JSON.stringify(mySCI);

Remember that while most browsers support JSON natively, older ones may not. You can include Douglass Crockford's JSON-js script for compatibility.

Edit:

Based on the screenshot provided, it appears that values are stored under the key simpleCart_items in localStorage (not your_json as used in the code) and object keys follow a pattern like "SCI-1". To work with this structure:

 $("#matkahuolto").click(function(){
    var value_object = {quantity: 1, id: 1, name: "someName"} ; 
    var jsonObject = JSON.parse(localStorage["simpleCart_items"]);
    json_object["SCI_1"] = value_object; // add value

 localStorage["simpleCart_items"] = JSON.stringify(json_object);  // store it again.

});

$("#posti").click(function(){
 // convert string to object
 var json_object = JSON.parse(localStorage["simpleCart_items"]); 

json_object["SCI-1"] = value_object; // add value

 localStorage["simpleCart_items"] = JSON.stringify(json_object);  // store it again.

});

Answer №2

When using LocalStorage, keep in mind that all data is stored as a string of text. It's best to make modifications before it gets converted into a string.

If you need to add a property to the JSON string, you'll have to first convert it into an object, add the property, then convert it back to a string for storage.

Code Example

var json_obj = JSON.parse(localStorage.your_data); // turn string into object
json_obj[key] = value; // add the property
localStorage.your_data = JSON.stringify(json_obj);  // store it again.

Important Note

Consider using indexedDB as an alternative solution.
It offers more flexibility and robustness compared to LocalStorage.

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

Pre-rendering Vue.js for SEO with prerender-spa-plugin becomes unresponsive during the npm run build process

My current issue arises when attempting to execute the command npm run build while utilizing the pre-rendering plugin in my webpack configuration. I incorporated some advanced options in webpack such as: `captureAfterDocumentEvent: 'fetch-done' ...

What is the optimal method for verifying two distinct conditions simultaneously using Javascript?

Hey there, I'm working on a code snippet to check the status of a Rails model. Here's what I have so far: var intervalCall = setInterval(function(){ $.post("getstatus", {id:id}); var finished = "<%= @sentence.finished%>"; // CONDI ...

Tips for showcasing a blurry image in NextJS while it's in the process of being fetched?

Is there a way to achieve a similar effect like the one showcased below? https://i.sstatic.net/9unuN.gif I've managed to do something similar with Gatsby, but I'm curious if it's achievable with NextJS as well. ...

Frontend is refusing to remove items from the shopping cart, while the backend is functioning properly in doing so

I've been working on a shopping cart project using Vanilla JS. The interface handles DOM logic, while the backend deals with array manipulation. The issue I'm facing is with a button that's supposed to remove items from the cart. Despite pa ...

3 Methods for Implementing a Floating Header, Main Content, and Sidebar with Responsive Design

I am following a mobile-first approach with 3 containers that need to be displayed in 3 different layouts as shown in the image below: https://i.sstatic.net/UjKNH.png The closest CSS implementation I have achieved so far is this: HTML: <header>.. ...

Obtain the total number of result entries

I'm working on a project involving JS and PHP. My goal is to call a PHP file using Ajax and have it return the count of result lines. I use echo for this: $connection = new PDO($source, $user); $query = "SELECT * FROM scores WHERE username = '" ...

Establishing a standard flatiron-director route (within the element) using the polymer core-pages component

This particular query is closely linked with issues surrounding the usage of flatiron-director/core-pages SPA in conjunction with route-specific JavaScript functions and default routes. While the solution proposed may be effective, my limited expertise in ...

Exporting ExpressJS from a TypeScript wrapper in NodeJS

I've developed a custom ExpressJS wrapper on a private npm repository and I'm looking to export both my library and ExpressJS itself. Here's an example: index.ts export { myExpress } from './my-express'; // my custom express wrap ...

Is there a way to change the value of "this. props.history.location.pathname" programmatically without causing a page refresh?

I'm currently developing a small extension for my map-based project. This extension is intended to display the latitude and longitude of a place in the URL like this whenever the user changes location. The issue lies in my inability to modify the pat ...

Tips for incorporating a hashbang into a JavaScript file that is executable without compromising browser compatibility

Is it possible to run code like this in both Node.js and the browser? #! /usr/local/bin/node console.log("Hello world") I have a script that I currently run locally in Node.js, but now I want to also execute it in the browser without having to modify it ...

Challenges with loading times in extensive AngularJS applications

We are currently tackling performance issues related to the loading time of our AngularJS application. The page takes a significant amount of time to load, and we are exploring potential causes for this delay. One factor that could be contributing to the ...

The object underwent modifications after being handed off to another function

Is it possible for an object to be altered after being passed to another function? For instance: var app = require('express')(); var http = require('http').Server(app); app.get('/', function (request, response) { respons ...

The functionality of the MVC jQuery grid is currently malfunctioning

Recently, I attempted to integrate a jQuery grid plugin from gijgo.com into my MVC application. Following the instructions provided on c-sharpcorner and/or codeproject meticulously, however, upon running the application, I encountered a troubling JavaScrip ...

Retrieve information without causing a complete page reload

Scenario: A customer buys an airline ticket from American Airlines on my website. After a processing time of one hour, I want to display a navigation tab without requiring the user to refresh the page. Inquiry: Is there a method to automatically trigger a ...

What is the best way to assign values to an array within a loop?

I've been struggling to figure out how to set the value of an array inside a loop... Below, you can see that I'm fetching some data from a database and iterating through it. The process I'm attempting to describe can be summarized as follo ...

Steps to integrate JavaScript with PayPal to accept payments in the requested currency

At this time, my website can only process payments in one currency using the following code <script src="https://www.paypal.com/sdk/js?client-id=Your Client ID&currency=AUD"></script> --> If I adjust it to USD like so... <s ...

The life cycle of the request/response object in Express.js when using callbacks

Feel free to correct me if this question has already been asked. (I've done as much research as I can handle before asking) I'm really trying to wrap my head around the life cycle of request and response objects. Take a look at the following co ...

What could be causing the issues with SSL certificates when using Node.js/Express-TypeScript?

I'm currently in the process of transitioning a project's backend from JavaScript (Node.js/Express) to TypeScript. However, I've encountered an unusual issue where FS's readFileSync is unable to access the key.pem or cert.pem files in t ...

What is the best way to showcase the user's input on the screen

Can anyone assist me in showing my user input from various types of form elements like textboxes, radio buttons, checkboxes, and dropdowns in a JavaScript alert box upon clicking the submit button? I am struggling to figure out how to achieve this function ...

Employ various iterations of the leaflet library

Creating a web application using React and various libraries, I encountered an issue with conflicting versions of the Leaflet library. Currently, I am incorporating the Windy API for weather forecast, which utilizes Leaflet library version 1.4.0. However ...