简体   繁体   中英

How can I test for localStorage value in this example?

when I do localStorage.getItem('user'); I receive this as value:

{
    "userDetails": {
        "gender": "",
        "language": "de",
        "color":
      }
}

I need to match my logic according to the language value. For example if "language": "de" do something, if "language": "en" do something else.

How can I match the value in key in my example?

Thanks.

getItem will return a string , so the first thing to do is parse it:

var data = JSON.parse(localStorage.getItem("user"));

Assuming your data is valid JSON (the text in the question isn't but looks like it's meant to be, it's missing a value for "color": ), that will return the parsed data.

Now you have an object with a property called userDetails which, in turn, has a property called language , so you can access it via data.userDetails.language , perhaps in a switch :

switch (data.userDetails.language) {
    case "de":
        // ...
        break;
    case "en":
        // ...
        break;
}

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