javascriptjsonsessionstorage

How to access record from sessionStorage by id/key?


I have data that is saved in sessionStorage and here is example of how I save data in sessionStorage.

$.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);
});

Once records are saved in sessionStorage they look 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"
  }
}

As you can see each record has unique key, once user decide to edit record all I have to do is pull data from sessionStorage and pass id that is matching unique key. Here is example of my edit function:

function editBook() {
    var recordID = $(this).closest('tr').attr('id'), // This id will be retrieved from presentation table. Each row has unique id that match sessonStorage.Books records.
        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);
            }
        });
    }
}

For some reason after I console.log() bookRecord I'm not getting data for specific id that I passed in sessionStorage. I'm not sure if my syntax is correct or something else might be the problem. I'm following the same steps as JS object is using to access records based on unique key. If anyone see where is the problem in my code please let me know.


Solution

  • The object is the result of JSON.parse(), you need to put the indexing there.

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