简体   繁体   中英

How to retrieve the JSON Data from localStorage

I'm trying to make a function that allow me to save variables using JSON.stringify, my code can save the data in localStorage, but, I don't know how can I retrieve it.

here is my code:

<body>
<button id="btn"> SAVE </button>

<script>
if(btn){
  btn.addEventListener("click", function(){saveSession();})
}
function saveSession(){
 var session = {'myValues': [],'state': true};
 session.myValues.push({ 'value 1': '50'});
 session.myValues.push({ 'value 2': '100'});
 session.myValues.push({ 'value 3': '150'});
 alert("saved");
 localStorage.setItem('session', JSON.stringify(session));
 var restoredSession = JSON.parse(localStorage.getItem('session'));
}
</script>
</body>

This code save the data in localStorage, but, what I want now is get the saved data value 1 and assign its value, that would be 50 to some variable, lets say I have var myValue and value 1 its equal 50, so, myValue would be 50. How can I do this?thanks in advance.

 function getValue(key) { // Get the session object and parse it var session = JSON.parse(localStorage.getItem('session')); // Seperate out myValues var myValues = session.myValues; // Filter out values that don't have a key equal to the key provided var filteredValue = myValues.filter(item => item.hasOwnProperty(key)); // Based on the example you provided there should only be one item with that key so return the first item in the filtered array return filteredValue[0]; } var myValue = getValue('value 1'); 

So the above should give you the result you are looking for. That said it is unnecessarily difficult due to the structure of your data. Are myValues just key-value pairs? If so why not just say

session.myValues['value 1'] = '50';
session.myValues['value 2'] = '100';
session.myValues['value 3'] = '150';

Furthermore, it isn't good practice to use a string that has a space as a key. It requires that you access if via to bracket notation. An alternative would be

session.myValues.value1 = '50';
session.myValues.value2 = '100';
session.myValues.value3 = '150';

Finally, if you do the above the getValue function becomes a lot simpler...

 function getValue(key) { var session = JSON.parse(localStorage.getItem('session')); return session.myValues[key]; } var myValue = getValue('value 1'); 

You are probably asking -- well you still used bracket notation...? Whenever the key is being accessed dynamically that is a requirement. So either naming option above still works... But it typically just isn't encouraged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM