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

问题描述 投票:-1回答:1

How can I access to a localStorage item?

在这种情况下,我在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"
  }
]

请任何人都可以帮助我。我想从localStorage数据访问它。

javascript json angular ionic3
1个回答
1
投票

您可以使用Storage界面的localStorage方法访问getItem数据。

// 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

了解更多关于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');
© www.soinside.com 2019 - 2024. All rights reserved.