Ensuring that localStorage objects continue to iterate when clear() is called within the same function

When a user completes the game loop or starts a new game, I want to clear all local storage while still keeping certain values intact.

Currently, I am able to do this for sound volume values:

// code inside a conditional statement triggered when starting a new game
if (newGameBool === '1') {
    var tst = myAu;
// myAu is the stored sound value set by the user using an input range

    localStorage.clear();

    localStorage.setItem("Au", tst); // After clearing local storage, set the same value again 

    UI.myLoad(); // Reload function that interacts with local storage

}

How can I achieve the same for keys with iterating numbers attached to them?

Here is how I save these keys:

var i = +v + +1; 

localStorage.setItem("v", i);

var vv = localStorage.getItem("v");

localStorage.setItem("LdrBrd_" + vv, JSON.stringify(LdrBrd)); // Saves data with iterating key names

Implementing retrieval similar to the sound function:

var gv = v + 1; // Retrieve the value from local storage and adjust for off-by-one error. gv is a local variable.
if (newGameBool === '1') {
    var ldd, vg;

    for (var ii = 0; ii < gv; ii++) {
        var ld = localStorage.getItem("LdrBrd_" + ii);
        if (ld != null) {
        // Values to retain beyond the clearing point
            ldd = JSON.parse(ld); // Parse saved JSON string data
            vg = ii; // Number of values retrieved
        }

    }

    localStorage.clear();

    for (var xx = 0; xx < vg; xx++) {
        var nld = localStorage.getItem("LdrBrd_" + xx);
        if (nld != null) {
           localStorage.setItem("LdrBrd_" + ii, JSON.stringify(ldd));
        }
    }
    localStorage.setItem("v", vg);

    UI.myLoad();

}

I have been using console.log() at different points to monitor the process. I commented out the clear function just to check if the values were incorrect, but they did not save at all. I attempted to create a fiddle, but local storage was not functioning there. In Visual Studio, everything works fine, but the script for this file is nearly 2000 lines long, so I tried to organize it as best as I could.

Thank you in advance for any assistance or advice.

Answer №1

After spending several days stuck on this issue, I believe I have found a solution that works. In the spirit of posterity, I will provide an answer to my own question.

localStorage.clear();
/*  ^LS clear() function is above all new setItem codes, some variables are declared globally and some are declared at the top of the functional scope or as param^  */
var itemClass = document.querySelectorAll(".itemClass");//the strings are here

if (itemClass) {//make sure some exist
    for (var p = 0; p < itemClass.length; p++) {//count them
        mdd = JSON.parse(itemClass[p].innerText);//parse the data for saving

        localStorage.setItem("v", v);//this is the LS item that saves the amount of items i have, it's declared at the top of the functions timeline.
        localStorage.setItem("LdrBrd_" + p, JSON.stringify(mdd));//this setItem function will repeat and increment with 'p' and assign the right string back to the key name it had before.
    }
}

The key approach is to link the strings directly to an element by calling the class name. I then ran a loop to count them. 'mdd' captures each desired item. Finally, the items are reset to their original state.

This method has enabled me to create a system for users to collect trophies, which persist even after clearing the localStorage when starting a new game.

I utilized CSS to hide the text from the string.

color:transparent;

In my gameLoop, there is a function that reads the saved strings and displays them as cards beneath the hidden strings.

https://i.sstatic.net/EaaU7.png

Answer №2

To maintain certain values, I suggest following one of these two approaches:

  1. Avoid using localStorage.clear() and instead selectively remove the values you don't want by using

    localStorage.removeItem('itemName')
    . If your item names have a numeric aspect, consider implementing this in a loop to streamline the process.

  2. Prioritize saving the specific item(s) you want to keep before executing clear(), then restore them afterwards. This method is more suitable when there are significantly more items to be deleted than retained (refer below).

function mostlyClear() {
    var saveMe = {};
    saveMe['value1'] = localStorage.getItem('value1');
    saveMe['anotherValue'] = localStorage.getItem('anotherValue');
    localStorage.clear();
    for(var prop in saveMe) {
        if(!saveMe.hasOwnProperty(prop)) continue;

        localStorage.setItem(prop, saveMe[prop]);
    }
}

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 replicate the function of closing a tab or instance in a web browser using Protractor/Selenium?

I want to create an automated scenario where a User is prompted with an alert message when they try to close the browser's tab or the browser itself. The alert should say something like "Are you sure you want to leave?" When I manually close the tab ...

Exploring ways to locate values within a Python list

I am facing an issue while trying to append values from my JSON file. Even though I have successfully appended key2 and key3, I encountered a TypeError: list indices must be integers, not str when attempting to append value1 and value2 from key1. This is ...

Issues arise when attempting to determine the accurate dimensions of a canvas

Looking at my canvas element: <canvas id='arena'></canvas> This Element is set to fill the entire website window. It's contained within a div Element, both of which are set to 100% size. I attempted running this script: var c ...

How to easily toggle multiple elements using jQuery

I'm having trouble getting this block of code to function properly: $("a.expand_all").on("click",function(){ $(this).text('Hide'); $('.answer').each(function () { $(this).slideDown(150, function () { $( ...

What is the best way to store the outcome of a promise in a variable within a TypeScript constructor?

Is it possible to store the result of a promise in a variable within the constructor using Typescript? I'm working with AdonisJS to retrieve data from the database, but the process involves using promises. How do I assign the result to a variable? T ...

Exploring Jasmine's Powerful Spying and Mocking Capabilities in JavaScript Prototypes

Hey everyone, I need some help with a JavaScript issue. So, I have a file named FileA.js which contains a prototype called FileAObject.prototype along with a function named funcAlpha(). Here's a snippet of what it looks like: File = FileA function s ...

using eloquent in vuejs to fetch database columns

I am currently attempting to retrieve data from a database using an AXIOS get request. I have two models, Content and Word, which have many-to-many relationships. In my controller, I am trying the following: public function fetchCourses(){ $dayOne = C ...

What is the process of retrieving the JSON array containing data from Reddit?

I am struggling to grasp the idea of JSON arrays and how to pinpoint a specific array from a JSON response. My objective is to retrieve the "URL" key value from the "data" objects within the "children" array at http://www.reddit.com/r/gifs/.json, but I am ...

Changing a list into a specific JSON format using Python

I've encountered an issue where my output looks like this: List containing a long string ["21:15-21:30 IllegalAgrumentsException 1, 21:15-21:30 NullPointerException 2, 22:00-22:15 UserNotFoundException 1, 22:15-22:30 NullPointerException 1 ...

Requesting information from a NodeJs endpoint

I have a NodeJs application that requires calling an end-point (http:\localhost:9900\get\employee - asp.net web-api) to retrieve data. What are some options available for achieving this task? Is it possible to utilize promises in this scenar ...

How can AngularJS achieve ng-repeat functionality with multiple variables similar to ng-init?

When using ng-init, you have the ability to utilize multiple variables: ng-init="var1=value1; var2=value2" I attempted something similar with ng-repeat but unfortunately it did not work as expected ng-repeat= "var1 in var1s; var2 in var2s" Is there a p ...

Discovering the amount of attributes possessed by an element with jQuery

If I have an xml element like this: <fruit color="blue" taste="sweet" shape="round"></fruit> Without using jQuery, I could use the following code: fruit.attributes.length How can I achieve the same result with jQuery? ...

How can I save variable values to a text file or Excel file using Cypress.io?

Is there a way to write the values of a variable on a Text or Excel sheet? I have a variable called tex that stores string values, and I want to output these values onto text files or an Excel sheet if possible. beforeEach(() => { cy.visit('ht ...

Sending JsonObject responses in a Spring RESTful web service

I have integrated the spring framework into my project. Within the Websphere server, I have a webservice that looks like this: @RequestMapping (value="/services/SayHello2Me" , method=RequestMethod.GET, headers="Accept=application/json") @ResponseBody publ ...

I am facing an issue with resolving services in my AngularJS controller

Having trouble resolving the service data in AngularJS controller. var kattaApp = angular.module('kattaApp', []).controller('kattaController', function($scope, dataFactory) { var promise = dataFactory.getResult().then(function(data ...

How come the date displays as 21/1/2015 instead of 21/1/2015 in Android after parsing the JSON data?

Currently, I am utilizing the DatePicker functionality in my code and transmitting the value via JSON. The desired format for the value is 21/1/2015 without the extra backslashes. How can I resolve this issue? DatePickerDialog.OnDateSetListener date = n ...

Is there a way for me to provide the product ID based on the selected product?

Is there a way to store the IDs of selected products in a dynamic form with multiple product options? I am able to see the saved products in the console.log(fields, "fields");, but how can I also save the selected product IDs? Any guidance on th ...

What could be causing my form to malfunction when attempting to submit data using Ajax and an external PHP script that is handling two string inputs?

Hello, I am facing an issue while trying to utilize Ajax to interact with a PHP file and submit both inputs (fullname and phonenumber). When I click the submit button, it simply refreshes the page without performing the desired action. Below is the code I ...

Transform Promise-based code to use async/await

I'm attempting to rephrase this code using the async \ await syntax: public loadData(id: string): void { this.loadDataAsync() .then((data: any): void => { // Perform actions with data }) .catch((ex): v ...

How can I leverage Express, AngularJS, and Socket.io to facilitate broadcasting and receiving notifications?

A new notification system is in the works. To illustrate, User 1 is initiating a friend request to User 2. The technologies being utilized include express.js, angularjs, and socket.io. When User1 clicks the button, a request is sent. On User2's end, a ...