简体   繁体   中英

Using LocalStorage key to call object value

Basically I have a local storage key "rhand" with the value "sword4", and an object named sword4.

I want this to be dynamic so i can switch out item name in the local storage, such as "sword1", "sword2" and then have that bring up the unique information of the one equipped in the div.

i can put in sword4.name; and it will bring up the name "steel sword" but rhand1.name; does not do that, it says undefined...

im more familiar with PHP and it seems like this would work in PHP, but its not making sense in JavaScript. Sorry if my English is hard to understand.

Here is the code:

 localStorage.setItem("rhand", "sword4"); let sword4 = { name: "steel sword", info: "a sharp steel sword", def: "0", str: "10", int: "0", agi: "0", lbs: "3" }; let rhand1 = localStorage.getItem("rhand"); document.getElementById("rhand").innerHTML = rhand1.name;
 <div id="rhand"></div>

let sword4 = {
  name: "steel sword",
  info: "a sharp steel sword",
  def: "0",
  str: "10",
  int: "0",
  agi: "0",
  lbs: "3"
};
localStorage.setItem("rhand", JSON.stringify(sword4));

let rhand1 = JSON.parse(localStorage.getItem("rhand"));
document.getElementById("rhand").innerHTML = rhand1.name

Try this and please close the question once it is done.

localStorage can only store Strings so when you need to store something other than String like an Array, Object, or Number -- convert it into a String with JSON.stringify() . When you want to retrieve something from localStorage convert it back with JSON.parse() .

Demo

Note: SO does not allow WebStorage API. For a fully functional demo see this Fiddle

 let sword4 = { name: "steel sword", info: "a sharp steel sword", def: "0", str: "10", int: "0", agi: "0", lbs: "3" }; localStorage.setItem("rhand", JSON.stringify(sword4)); let rhand1 = JSON.parse(localStorage.getItem("rhand")); document.getElementById("rhand").innerHTML = rhand1.name;
 <div id="rhand"></div>

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