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

Tips for optimizing large image files on a basic HTML, CSS, and JavaScript website to improve site speed and ensure optimal loading times

Currently, my site is live on Digital Ocean at this link: and you can find the GitHub code here: https://github.com/Omkarc284/SNsite1. While it functions well in development, issues arise when it's in production. My website contains heavy images, in ...

Issue with React Ref: Invariant Violation when trying to addComponentAsRefTo

I'm encountering an issue while attempting to add a ref to a React component. The error message I'm seeing is as follows: invariant.js:39Uncaught Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding ...

Vue js homepage footer design

I am struggling to add a footer to my Vue.js project homepage. Being an inexperienced beginner in Vue, I am finding it difficult to make it work. Here is where I need to add the footer Below is my footer component: <template> <footer> </ ...

Exploring the Live Search Functionality on an HTML Webpage

I am attempting to create a live search on dive elements within an HTML document. var val; $(document).ready(function() { $('#search').keyup(function() { var value = document.getElementById('search').value; val = $.trim(val ...

ORA-02201 You can't use a sequence in this context

Greetings everyone. I'm encountering a persistent "ORA_02201 - Sequence is not allowed here" SQL syntax error whenever I attempt to insert a new entry into the Database using JSON on my Oracle Autonomous Database. It's common practice in the Orac ...

It is impossible to alter the data contained within the input box

Objective: Upon clicking a button to display the modal, the selected data (first and last name) should be inserted into an input box and editable. The user should be able to modify the data. Issue: The data entered into the input box cannot be edited ...

Angular image source load test encountered an error

<div class="col-xs-4 col-sm-4 col-md-4"> {{jsonData[current].profilepic}} <div ng-if=IsValidImageUrl(jsonData[current].profilepic)> <img id="pic" ng-src="{{jsonData[current].profilepic}}" alt=""/> </div> < ...

updating the count of items in a react virtual list

Popular libraries such as react-virtualized, react-window, and react-virtuoso all include an item count property similar to the one shown in the code snippet below from material-ui. However, this property is typically located within the return statement. ...

Can we safely save a value in session storage directly from the main.js file in Vue?

Throughout the user session managed by Vuex, I have a session storage value set to false that needs to be monitored. Setting up this value directly from the main.js file looks like this: import { createApp } from 'vue'; import App from './Ap ...

What is the process for importing a React component that relies on a dependency?

This is my first experience using React (with babel) and jsx, along with Webpack to create my bundle.js I have developed two React components - Header1.jsx and Header2.jsx. The logic I want to implement is as follows: If the date is before July 4th, 2016 ...

Delete elements with identical values from array "a" and then delete the element at the same index in array "b" as the one removed from array "a"

Currently, I am facing an issue while plotting a temperature chart as I have two arrays: a, which consists of registered temperature values throughout the day. For example: a=[22.1, 23.4, 21.7,...]; and b, containing the corresponding timestamps for eac ...

Convert image buffer to string using Mongoose getter?

I have developed a basic node backend application modeled after eBay. I am now working on creating a react frontend app to complement it. Within the app, users can list items for sale and include a photo with their listing. The item information is stored ...

The HTML status code is 200, even though the JQuery ajax request shows a status code of 0

My issue is not related to cross site request problem, which is a common suggestion in search results for similar questions. When attempting to make an ajax request using jquery functions .get and .load, I'm receiving xhr.status 0 and xhr.statusText ...

I'm wondering if there is a method for me to get only the count of input fields that have the class "Calctime" and are not empty when this function is executed

Currently, I am developing an airport application that aims to track the time it takes to travel between different airports. In this context, moving from one airport to another is referred to as a Sector, and the duration of time taken for this journey is ...

Ways to showcase INPUT TYPE when making a Selection?

I've been struggling with a simple issue and despite trying multiple solutions, I can't seem to get it right. I have a form where I'm using the <select> tag with two options: coo and uh. What I want is for an additional input type fiel ...

Issues encountered when incorporating personalized CSS into a Vuetify element

Working with the Vuetify selector input component, v-select, and wanting to customize its style led me to inspecting it in Chrome and copying down the necessary classes. For instance, to change the font size of the active value, I utilized: .v-select__sel ...

The Add/Remove button functionality is not functioning as expected for duplicated form fields when using jQuery

I am experiencing an issue with the functionality of the "Add another" and "Remove row" buttons in my form. I implemented code from a specific Stack Overflow answer (jquery clone form fields and increment id) to create a cloneable section, but only the ori ...

Having trouble integrating Backbone-relational with AMD (RequireJS)?

I'm struggling with my Backbone router and module definitions in CoffeeScript. Can someone help me troubleshoot? // appointments_router.js.coffee define ["app", "appointment"], (App) -> class Snip.Routers.AppointmentsRouter extends Backbone.Rout ...

Guidelines for iterating through a nested JSON array and extracting a search query in Angular

I'm currently working with a complex nested JSON Array and I need to filter it (based on the name property) according to what the user enters in an input tag, displaying the results as an autocomplete. I've started developing a basic version of t ...

Encountering an issue when attempting to host a Next.js application on Vercel

Why is it important to regularly do this task as per the instructions provided in the link? Info - Working on creating a highly efficient production build... Note: Next.js now collects completely anonymous telemetry data on user usage. This data helps sha ...