So I want to iterate over a JSON object stored in my Local storage of the browser. Basically the JSON object looks and is added like this:
if (localStorage.getItem("playerHighscoreObject") == undefined) {
playerHighscoreList = [
{'name': "Ben", 'score': 40},
{'name': "Joe", 'score': 44},
{'name': "Anna", 'score': 51},
{'name': "Mitch", 'score': 59},
{'name': "Abdi", 'score': 63}
];
localStorage.setItem("playerHighscoreObject", JSON.stringify(playerHighscoreList));
}
else {
playerHighscoreList = localStorage.getItem("playerHighscoreObject");
}
I then want to iterate over the object and check for the "score" key and compare the values to a potential new entry.
function saveScore() {
var key = "score";
console.log(playerHighscoreList);
for (key in playerHighscoreList) {
if (playerHighscoreList.hasOwnProperty(key)) {
var val = playerHighscoreList[key];
console.log(val);
}
}
}
However when I do this I get 135 undefined in the log. Even though I print the JSON object and it shows up as it should be
[{"name":"Ben","score":40},{"name":"Joe","score":44},{"name":"Anna","score":51},{"name":"Mitch","score":59},{"name":"Abdi","score":63}]
What am I doing wrong here?
EDIT: Suggested duplicate uses jQuery to solve the problem. I do not wish to use jQuery, but vanilla javascript as described in the title.