Finding specific data in sessionStorage using an ID or key

I have stored data in sessionStorage and this is an example of how I save the data:

$.ajax({
    type: 'POST',
    url: 'Components/Functions.cfc?method='+cfMethod,
    data: formData,
    dataType: 'json'
}).done(function(obj){
    sessionStorage.setItem('Books',JSON.stringify(obj.DATA));
}).fail(function(jqXHR, textStatus, errorThrown){
    alert('Error: '+errorThrown);
});

After saving records in sessionStorage, they are structured like this:

{
  "14": {
    "COMMENTS": "",
    "RECORDID": 14,
    "NAME": "Decorah Sector",
    "AGENCY": "01",
    "CODE": "011A"
  },
  "15": {
    "COMMENTS": "",
    "RECORDID": 15,
    "NAME": "Waukon Field",
    "AGENCY": "01",
    "CODE": "011B"
  },
  "16": {
    "COMMENTS": "Test 524",
    "RECORDID": 16,
    "NAME": "New Hampton",
    "AGENCY": "01",
    "CODE": "011C"
  }
}

Each record has a unique key. When a user wants to edit a record, I retrieve the data from sessionStorage using the matching unique key. Here's an example of my edit function:

function editBook() {
    var recordID = $(this).closest('tr').attr('id'),
        bookRecord = JSON.parse(sessionStorage.Books[recordID]);
        console.log(bookRecord); //For testing purpose.
    if(bookRecord){
        $.each(regionRecord, function(name, value){
            var elementName = $('[name="'+'frmSave_'+name.toLowerCase()+'"]'),
                elementType = elementName.prop('type'),
                elementVal = $.trim(value);

            switch(elementType){
                case 'select-one':
                    elementName.val(elementVal);
                    break;
                case 'textarea':
                    elementName.val(elementVal);
                    break;
                default:
                    elementName.val(elementVal);
            }
        });
    }
}

When I console.log() bookRecord, I'm not receiving the data for the specific id that I passed in sessionStorage. I'm unsure if there's an issue with my syntax or something else causing the problem. If anyone can identify where the issue might be in my code, please advise.

Answer №1

The outcome is derived from executing the JSON.parse() function, make sure to include the indexing within it.

bookRecord = JSON.parse(sessionStorage.Books)[recordID];

Answer №2

When working with JSON data stored in the session storage, it is important to access the correct object record by making a slight adjustment to the code.

bookRecord = JSON.parse(sessionStorage.Books)[recordID];

This change ensures that you are accessing the specific object record that has been parsed from the JSON data, allowing for accurate retrieval of information.

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

Exploring the application of the PUT method specific to a card ID in vue.js

A dashboard on my interface showcases various cards containing data retrieved from the backend API and stored in an array called notes[]. When I click on a specific card, a pop-up named updatecard should appear based on its id. However, I am facing issues ...

Custom palette in Material UI design palette allows users to create

Hey there everyone! I've been working on a website using ReactJS and Material UI, starting with this cool template. One thing I'm trying to do is change the color of the TextField when it's focused. Right now it's blue, but I want it ...

``Is there a way to access the $attrs data of child DOM elements from within a controller?

Imagine having a controller and multiple children DOMs each with their unique data attributes. <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> < ...

Utilizing Spring Data REST with raw JSON (non-HAL structure)

Is there a way to configure Spring Data Rest to return plain JSON instead of HAL (JSON with Hypermedia like links)? Here are some related resources: Spring returns Resource in pure JSON not in HAL Format when including spring data rest Spring Data Rest ...

Issue: Retrieve comments via AJAX (from database) in Laravel 5.2

Currently, I am developing a comments section for posts where users can leave comments without the need to refresh the page. However, I am facing an issue in displaying these comments instantly on the post without any page refresh. This is how I have stru ...

Encountering an issue with Node JS request and cheerio while parsing an HTML page

Greetings all, I am currently attempting to parse a website using Node.js (utilizing request and cheerio). The issue I am encountering is that I am trying to extract the href from the site, but I can only find it within the site's window. Unfortunatel ...

Error in Javascript: Null Object

I have created an upload page with a PHP script for AJAX, but I'm encountering errors in Firebug. Also, the upload percentage is not being returned properly. Currently, I can only do one upload in Firefox and the script doesn't work in Chrome. H ...

Using JQuery to reveal a hidden child element within a parent element

I'm facing a challenge with displaying nested ul lists on my website. The parent ul is hidden with CSS, causing the child ul to also remain hidden even when I try to display it using jQuery. One approach I've attempted is adding a class to the f ...

What is the best approach to updating a single item within a list using React Context?

React context is great, but I feel like there's something missing in my understanding of it. Let's say I have a list of todos and its corresponding provider set up like this: const Home = () => ( <div className="container"> <T ...

The callback function in JavaScript seems to be missing without ever being executed

I have a SendMail function using nodemailer that successfully sends emails, but the callback function logging "mail sent" is not getting executed. Any suggestions on what might be causing this? var email = '<a href="/cdn-cgi/l/email-protection" cla ...

A method for dynamically enlarging a parent node within a dhtmlx tree using JSON data

As I was browsing through the dhtmlx documentation, I came across this particular method: This method determines how the server-side URL is constructed when making dynamic loading calls: <script> tree.setXMLAutoLoadingBehaviour(mode); </s ...

JavaScript Thumbnail Slider Builder

I've been working hard on developing a custom JavaScript thumbnail slider that uses data-src. Everything seems to be in order, except the next and previous buttons are not functioning properly. Any assistance would be greatly appreciated. Here's ...

The cross-origin resource sharing (CORS) functionality is functioning properly on the

I've encountered an unusual problem with express cors. While my Cors configuration works perfectly on localhost, it fails to function in the production environment. Every time I encounter the same error. Failed to load : Response to preflight r ...

Configuring lazy loaded modules with Angular 2 router

I am in the process of developing a service that utilizes router configuration to generate a map of routes based on components. Everything works smoothly except when dealing with lazy loaded module routes. I'm stuck on how to retrieve routes from a l ...

Retrieving a single item from an array of objects with the help of body parser

I need assistance with sending an array of objects to a post route in my express app. Here is my form (written in ejs format): <form action="/archiveList/<%= list._id %>" method="POST"> <input type="hidden" name="list" value = <%= items ...

Minimizing repeated autofocus calls in material-ui's <TextField> component

In the realm of coding with material-ui, when dealing with the <TextField> component, it's important to keep in mind that the solution may actually lie within React itself. Let's paint a scenario where we're crafting a basic login for ...

How can I convert base64 data to a specific file type using React Cropper JS?

I have successfully implemented the crop functionality using react cropper js. Now, I am faced with a challenge of sending the cropped image as a file type. Currently, I can obtain the base64 string for the cropped image. However, when I submit the cropped ...

Protractor is able to achieve successful test results without actually executing the tests

SYMPTOMS When running Protractor, the tests pass successfully, but the pages do not load. Instead, they appear blank with "data:text/html" in the address bar (refer to the screenshot). Although the tests show as passed, there are 0 assertions being made. ...

What is the best way to utilize Jackson mapper with java.io.Serializable type fields?

I encountered a scenario where POJOs are inheriting from an abstract superclass that has methods like getId() and setId() defined with the type java.io.Serializable. When deserializing a JSON string to my concrete POJO classes, I face the following excepti ...

pressing the downward arrow does not cause the number to decrease

I'm facing an issue with my code in this video. The increment is working when the upward arrow is clicked, but not the decrement. I suspect there's a problem with the jQuery code. Initially, I tried modifying from top to bottom, and changing +1 t ...