Return LocalStorage 键中的数组数

Return Number of arrays in LocalStorage Key

所以我知道还有很多其他帖子与此类似,但我已经仔细阅读了所有帖子,并且不断得到 Json 长度而不是数组的个数。

我试过了

function getLength(obj) {
  return (Object.values(obj)).flat().length
}

const lenObj = JSON.parse(localStorage.getItem('storeObj'));
var count = 0;
for(var item in lenObj) {
   count += lenObj[item].length
}
console.log("JSON obj length: ",count);
localStorage.keyname.length

这是我在 LocalStorage 中的通知密钥:

[{"id":1,"user":2},{"id":2,"user":2},{"id":6,"user":2},{"id":11,"user":2},{"id":12,"user":2},{"id":13,"user":2}]

目前无论我尝试哪种长度方法,我总是得到 112 的值而不是 6

这是我的代码:

 methods: {
    localStorage() {
      localStorage.setItem("Notification", JSON.stringify(this.notifications));
      console.log("works");
      console.log(this.notifications);
    }
  },
 getNames: function() {
      this.names = localStorage.getItem("Notification");
      console.log(this.names);
      *~code to return 6~*
    },

感谢您的帮助!

也许您使解决方案变得比需要的更复杂。如果您的通知看起来像那个对象数组,那么 - 没有存储 - 它就像解析 json 字符串并询问解析对象的长度一样简单。

let json = '[{"id":1,"user":2},{"id":2,"user":2},{"id":6,"user":2},{"id":11,"user":2},{"id":12,"user":2},{"id":13,"user":2}]';
let data = JSON.parse(json);
console.log(data.length);

所以你的 getNames 方法看起来像:

getNames: () => {
   this.names = JSON.parse(localStorage.getItem("Notification")); // array of objects
   return this.names.length; // return 6
}

你需要JSON.parse

let data = JSON.parse(localStorage.getItem("Notification") || ' [{"id": 1, "user": 2}, {"id": 2, "user": 2}, {"id": 6, "user": 2}, {"id": 11, "user": 2}, {"id": 12, "user": 2}, {"id": 13, "user": 2}]');
if (Array.isArray(data)) {//save into localStorage only if data is an array
    localStorage.setItem("Notification", JSON.stringify(data));
    let Notification = localStorage.getItem("Notification");
    let array_Notification = JSON.parse(Notification);
    console.log(Notification.length);//this will return 112, because it's a string
    console.log(array_Notification.length);//this will return 6 because it's an array
}else{
    localStorage.removeItem("Notification"); //something is not right , it's better to remove that dummy data
}