2

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>

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.