简体   繁体   English

localstorage json 行我如何访问每一行及其各个元素

[英]localstorage json rows how do i access each row and their individual elements

How can I access to a localStorage item?如何访问 localStorage 项目?

In this case I have the following array of objects in the localStorage:在这种情况下,我在 localStorage 中有以下对象数组:

[
  {
    "id1":"my_id",
    "title":"My_title",
    "subject":"subject1"
  },
  {
    "id2":"my_id",
    "title":"My_title2",
    "subject":"subject2"
  },
  {
     "id3":"my_id",
     "title":"My_title3",
     "subject":"subject3"
  },
  {
    "id4":"my_id",
    "title":"My_title4",
    "subject":"subject4"
  }
]

Please can anyone help me with this.请任何人都可以帮我解决这个问题。 I want to access this from localStorage data.我想从 localStorage 数据访问它。

You can access the localStorage data using the getItem method of the Storage interface.您可以使用 Storage 接口的getItem方法访问localStorage数据。

// just change [my-local-storage-data-key] string for your actual data key on localStorage
const data = localStorage.getItem("[my-local-storage-data-key]");
const jsonData = JSON.parse(data);
// -> jsonData holds your array of objects

Read more about localStorage .阅读有关localStorage 的更多信息。


 // copy the following to your browser console and check outputs // trying to run this code snippet will fail because the document is sandboxed and lacks the "allow-same-origin' flag." const myDataArray = [ { "id1":"my_id", "title":"My_title", "subject":"subject1" }, { "id2":"my_id", "title":"My_title2", "subject":"subject2" }, { "id3":"my_id", "title":"My_title3", "subject":"subject3" }, { "id4":"my_id", "title":"My_title4", "subject":"subject4" } ]; // saving to localStorage with `rows` as key const serializedData = JSON.stringify(myDataArray); localStorage.setItem('rows', serializedData); // retrieving data from localStorage `rows` key const data = localStorage.getItem('rows'); const jsonData = JSON.parse(data); console.log('jsonData from localStorage:', jsonData); // -> jsonData from localStorage: (4) [{…}, {…}, {…}, {…}] console.log('jsonData[0]:', jsonData[0]); // -> jsonData[0]: {id1: "my_id", title: "My_title", subject: "subject1"} // remove localStorage item `rows` localStorage.removeItem('rows');

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

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