简体   繁体   English

Javascript遍历本地存储JSON对象(Vanilla Javascript)

[英]Javascript iterate over local storage JSON object (Vanilla Javascript)

So I want to iterate over a JSON object stored in my Local storage of the browser. 所以我想遍历存储在浏览器本地存储中的JSON对象。 Basically the JSON object looks and is added like this: 基本上,JSON对象的外观和添加方式如下:

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. 但是,当我这样做时,我在日志中得到135 undefined。 Even though I print the JSON object and it shows up as it should be 即使我打印了JSON对象,它也应该显示出来

[{"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. 编辑:建议重复使用jQuery解决问题。 I do not wish to use jQuery, but vanilla javascript as described in the title. 我不希望使用jQuery,而是使用标题中所述的普通javascript。

Once you fix the problem that Dimava found and pointed out in a comment 修复Dimava发现并在注释中指出的问题后,

else {
    playerHighscoreList = JSON.parse(localStorage.getItem("playerHighscoreObject"));
    //                    ^^^^^^^^^^---- this was missing
}

(More on that below.) (更多有关以下内容。)

...then at its core, this has nothing to do with local storage or JSON. ...然后从根本上讲,这与本地存储或JSON无关。 You want to loop through an array of objects and access a property on the objects in the array. 您要遍历对象数组并访问数组中对象的属性。

The problem with your code is that 您的代码的问题是

  1. You're using for-in , which isn't for looping through arrays; 您正在使用for-in ,这不是用于遍历数组; my answer here has a complete rundown of ways to loop through arrays 我在这里的答案完整介绍了遍历数组的方法

  2. You're overwriting the value of key 您正在覆盖key的价值

  3. You're trying to make key do double-duty 您正在尝试使key承担双重职责

Instead, use any of the normal ways to loop through arrays, such as forEach : 相反,请使用任何常规方法来遍历数组,例如forEach

function saveScore() {
  var key = "score";
  playerHighscoreList.forEach(function(entry) {
    if (entry.hasOwnProperty(key)) {
      var val = entry[key];
      console.log(val);
    }
  });
}

About your retrieval of the object from local storage, you can make that a bit simpler: 关于从本地存储中检索对象,您可以使其变得更简单:

playerHighscoreList = JSON.parse(localStorage.getItem("playerHighscoreObject") || "null") || [
  {'name': "Ben", 'score': 40},
  {'name': "Joe", 'score': 44},
  {'name': "Anna", 'score': 51},
  {'name': "Mitch", 'score': 59},
  {'name': "Abdi", 'score': 63}
];

Once you've updated it, save it (no particular reason to save it before updating it, as your original code did): 更新后,将其保存(没有任何特殊原因,就像原始代码一样,在更新前也要保存):

localStorage.setItem("playerHighscoreObject", JSON.stringify(playerHighscoreList));

You might also consider making the local storage name and the variable name match. 您还可以考虑使本地存储名称和变量名称匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM