Search code examples
javascriptjsonobjectobject-literal

Why doesnt {highscorelist} have a value?


const HIGHSCOREKEY = "highscore";

highscorelist = localStorage.getItem(HIGHSCOREKEY);
if(highscorelist){
    highscorelist = {
        one: {navn: "AAA", score: 0},
        two: {navn: "AAA", score: 0},
        three: {navn: "AAA", score: 0}
    };
    localStorage.setItem(HIGHSCOREKEY, JSON.stringify(highscorelist));
};

this is the code for it, when i try to do "highscorelist.one.score" it says: "Uncaught TypeError: Cannot read property 'one' of null"


Solution

  • localStorage.setItem(HIGHSCOREKEY, JSON.stringify(highscorelist)); is equivalent to localStorage.setItem(HIGHSCOREKEY, highscorelist); as localStorage will store in the form of string.

    So while retriving the data do

    highscorelist = JSON.parse(localStorage.getItem(HIGHSCOREKEY));