Iterating over the local storage to locate a specific item

Utilizing local storage extensively has been beneficial for maintaining state by storing the session on the client side. However, a challenge arises when updating the session.

Within my code, there are multiple lists of objects that I serialize in JSON format and store in the session. These objects contain various properties such as an ID and a date. At one point in the application, it is necessary to iterate through these lists to determine if a specific object with a certain ID exists within any of them.

The naming convention for the key used to store the JSON data includes a date component, like so:

var TheData = JSON.stringify(TheListOfMyObjects);
var SessionKey = 'TheListOfObjectsFor' + TheMonth + "." + TheDay + "." + TheYear;
localStorage.setItem(SessionKey, TheData);

Now comes the task of searching for an object by its ID without knowing the corresponding date property. Additionally, there is uncertainty regarding which dates have associated values stored in the session.

Is there a method to locate the object based solely on its ID? It would be helpful if the session data could be loaded into memory for easier iteration.

Answer №1

To locate a specific ID within an object, you would have to iterate through each localStorage object and compare their respective fields.

var data1 = {ID  : "x",  value: 123}
var data2 = {ID  : "y",  value: 456}
var data3 = {ID  : "z",  value: 789}

localStorage.setItem("dataEntry1", JSON.stringify(data1));
localStorage.setItem("dataEntry2", JSON.stringify(data2));
localStorage.setItem("dataEntry3", JSON.stringify(data3));

var targetID = "y";

for(var j = 0; j < localStorage.length; j++) {

    var item = JSON.parse(localStorage.getItem(localStorage.key(j)));

    if(item.ID == targetID) {
        console.log(item);
        break;
    }
}

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

Sort the array in alphabetical and numerical order while meeting a specific condition

In my code, I am attempting to sort an array based on two conditions. Specifically, I need to ensure that Pos 10 comes after single digits and follows a specific order after that. Initially, I tried to prioritize strings containing the word first, but whe ...

AngularJS: Issue with JQuery Slider not Updating Scope Value

I am currently working on a project using AngularJS and I have integrated a jQuery slider into it. However, I am facing an issue where I need to change the value of a select box which is defined in a $scope array, but the functionality is not working as ex ...

The JSON POST Method is not allowed for a Self-Hosted WCF REST service

After encountering countless "WCF" questions online, I am starting to believe that finding a solution is nearly impossible. Can someone prove me wrong? My current situation involves working with a Self Hosted WCF Service where endpoints are defined progra ...

What is the most effective approach for addressing errors in both the server and client sides while utilizing nodejs and express?

Seeking the most effective approach for handling errors in a response - request scenario. Here is an example of a route that receives a request: app.get('/getInfo', function (req, res, next) { let obj = {} try { obj = { ...

Using a combination of stringify, regular expressions, and parsing to manipulate objects

As I review code for a significant pull request from a new developer, I notice their unconventional approach to editing javascript objects. They utilize JSON.stringify(), followed by string.replace() on the resulting string to make updates to both keys a ...

How to access selection range styles using JavaScript

It is common knowledge that we can retrieve the selection of text in JavaScript using the following method: var range = window.getSelection (); However, how can we obtain the style of this selection? For example, when I select bolded text or italicized ...

Guide on Linking a Variable to $scope in Angular 2

Struggling to find up-to-date Angular 2 syntax is a challenge. So, how can we properly connect variables (whether simple or objects) in Angular now that the concept of controller $scope has evolved? import {Component} from '@angular/core' @Comp ...

`Implementing Typescript code with Relay (Importing with System.js)`

Is there a way to resolve the error by including system.js or are there alternative solutions available? I recently downloaded the relay-starter-kit (https://github.com/relayjs/relay-starter-kit) and made changes to database.js, converting it into databas ...

Code snippet for adding a div element with an embedded image using JavaScript

I am attempting to create a function that generates three div elements, each containing an image, and then appends them to the body using a for loop. As a beginner in JavaScript, I am struggling with this task. Can anyone please provide guidance on what ...

Create a random number within a specified range using a different number in JavaScript

I am looking for a unique function that can generate a number within a specified range, based on a provided number. An example of the function would be: function getNumber(minimum, maximum, number) { ... } If I were to input: getNumber(0, 3, 12837623); ...

Transfer the values selected from checkboxes into an HTML input field

I am attempting to capture the values of checkboxes and then insert them into an input field once they have been checked. Using JavaScript, I have managed to show these values in a <span> tag successfully. However, when trying to do the same within a ...

Failure to execute after Ajax success

Currently working on a login page using Spring MVC on the server side and JS/Ajax on the client side. I'm facing an issue where the server code executes but does not return anything. <script type="text/javascript"> $(function() { $( ...

Using Jquery to loop through a function for every select box that is added dynamically

Encountering some challenges with jQuery while attempting to utilize the same function and iterate over select boxes that are dynamically generated with jQuery's clone() method. Here is a snippet of the content being cloned: <select name="expense ...

When making an XMLHTTPRequest, Chrome often responds with an "Aw, snap"

In the development of my server-based multiplayer game using three.js, I have set up the server to operate as follows: game->Server2.php->Server.txt game->Server.php->Server.txt->game The process flow is as follows: 1.) The game is gener ...

The functionality of anchor links created through ajax is not operating correctly

Issue: I am encountering a problem where I have a table filled via Ajax, containing local anchors. When an anchor is clicked, it should make a section visible and automatically scroll to it. This functionality works when manually filling the table, but not ...

Navigate to a new page on button click using Row with Tanstack / React-Table and Typescript (2339)

Encountering a linting error when attempting to navigate to a new route by clicking on a table row. The functionality is working but how can I resolve this issue? It's showing an error message stating "The property "id" for type TData does not exist." ...

What is the proper way to utilize the decodeURIComponent function?

router.get("/stocks/authed/:symbol", function (req, res, next) { req.db .from("stocks") .select("*") .modify(function(queryBuilder) { if (req.query.from && req.query.to) { queryBuilder.whereBetween('timestamp&apos ...

Creating enduring designs in Next.js

I've been diving into this amazing article and I'm puzzling over the implementation of persistence in Option 4. It seems like you would need to redefine the .getLayout method for each page. I'm uncertain about how nesting logic is handled fo ...

What are the reasons behind lang sass not functioning within the style tag of a .vue file?

Even though I had previously installed sass-loader and node-sass in my project, I encountered an issue when attempting to use <style lang="sass"> in my vue file. The style did not compile as expected, however it worked perfectly without the lang="s ...

Text centered on hover for figure caption

Check out this fiddle http://jsfiddle.net/sLdhsbou/ where I am trying to center the "x" that appears on hover perfectly no matter what size the image is. Also, why does the transition not occur when moving the mouse outside of the figure, unlike when movi ...