How to check if value exist in Local Storage data set?

梦想的初衷 提交于 2019-12-25 12:52:01

问题


I have done some research about local storage. Seems like a pretty good option to store data. In my Single Page App I use JSON to store some of the data that is used more than once in my app. I'm wondering if I can replace JSON with Local Storage? Also what would be the benefits? So far I was able to load data in Local Storage but I couldn't check if values exist in Local Storage and how I will read the data. Here is example:

$.ajax({
        type: 'POST',
        url: 'App.cfc?method='+getMethod,
        data: {'recID':recID},
        dataType: 'json'
    }).done(function(obj){
        var numRecs = obj.RECORDCOUNT;
        jsonData[recID] = obj.DATA;
        localStorage.setItem(recID,JSON.stringify(obj.DATA));

        var firstN = jsonData[recID].hasOwnProperty('F_NAME') == true ? $.trim(jsonData[recID]['F_NAME']['value']) : '',
        lastN = jsonData[recID].hasOwnProperty('L_NAME') == true ? $.trim(jsonData[recID]['L_NAME']['value']) : '';
        console.log(localStorage[recID] +'\n'+ localStorage[recID].hasOwnProperty("L_NAME")); //Check Local Storage if value exist

    }).fail(function(jqXHR, textStatus, errorThrown){
    if(jqXHR.status == 0){
        alert("Fail to connect. Please check your internet connection.");
    }else{
        alert("Error: "+errorThrown);
    }
});

Here is example of JSON and localStorage data:

{"F_NAME":{"value":"John"},"L_NAME":{"value":"Smith"}}

Both JSON and local Storage have the same structure after I dumped the data in the console but hasOwnProperty() indicates to false in my code example above where I test loacl storage in console. I'm wondering if my code is invalid or something else is causing my code to fail. Main reason why I would like to use local storage is situation when user loose internet connection. In that case I want to save form data in local storage that way user won;t lose the data. If anyone can provide example or help with any tips please let me know. Thank you!


回答1:


localStorage stores strings, which you know since you're already JSON.stringify()ing when you save. But you need to replace your check of

localStorage[recID].hasOwnProperty("L_NAME")

with

JSON.parse(localStorage[recID]).hasOwnProperty("L_NAME")

Edit: You have a whole object which you store as localStorage[recID], so you need to parse that, then access the resulting object, like:

const record = JSON.stringify({
  "F_NAME": {
    "value": "John"
  },
  "L_NAME": {
    "value": "Smith"
  }
});

console.log(JSON.parse(record)['F_NAME']['value'])

JSON.parse(record) becomes the object, then you access its descendant parameters ['F_NAME']['value']. The placement of the brackets is critical.



来源:https://stackoverflow.com/questions/47167393/how-to-check-if-value-exist-in-local-storage-data-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!