简体   繁体   中英

How can I set a value in an object based on if there's an entry in localStorage or not?

I have code that sets up my loginData object:

user.loginData = {
    userName: "",
    password: "",
    rememberMe: "",
    grant_type: "password",
};

Depending on if I have previously stored the userName into localStorage:

localStorage.userName = "Joe";

How can I make it so the loginData object has a userName of "" if there's nothing stored in localStorage and it use the stored value if there is something stored in localstorage?

Try this:

user.loginData = {
    userName: (localStorage.userName&&localStorage.userName.length>0) ? localStorage.userName : "",
    password: "",
    rememberMe: "",
    grant_type: "password",
};

localStorage.userName.length>0 ? localStorage.userName : "" translates to

if( localStorage.userName.length > 0 )
{
  user.loginData.userName = localStorage.userName;
}
else
{
  user.loginData.userName = "";
}

You need to have localStorage defined before filling user.loginData.

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