簡體   English   中英

HTML5 localStorage/sessionStorage中如何存儲對象

[英]How to store objects in HTML5 localStorage/sessionStorage

我想將 JavaScript object 存儲在 HTML5 localStorage中,但我的 object 顯然正在轉換為字符串。

我可以使用localStorage存儲和檢索原始類型 JavaScript 和 arrays,但對象似乎不起作用。 他們應該嗎?

這是我的代碼:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };
console.log('typeof testObject: ' + typeof testObject);
console.log('testObject properties:');
for (var prop in testObject) {
    console.log('  ' + prop + ': ' + testObject[prop]);
}

// Put the object into storage
localStorage.setItem('testObject', testObject);

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('typeof retrievedObject: ' + typeof retrievedObject);
console.log('Value of retrievedObject: ' + retrievedObject);

控制台 output 是

typeof testObject: object
testObject properties:
  one: 1
  two: 2
  three: 3
typeof retrievedObject: string
Value of retrievedObject: [object Object]

在我看來, setItem方法在存儲之前將輸入轉換為字符串。

我在 Safari、Chrome 和 Firefox 中看到了這種行為,所以我假設這是我對HTML5 Web 存儲規范的誤解,而不是特定於瀏覽器的錯誤或限制。

我試圖理解2 Common infrastructure中描述的結構化克隆算法。 我不完全明白它在說什么,但也許我的問題與我的對象的屬性不可枚舉有關(???)。

有簡單的解決方法嗎?


更新:W3C 最終改變了他們對結構化克隆規范的看法,並決定更改規范以匹配實現。 請參見12111 – 存儲規范 object getItem(key) 方法與實現行為不匹配 所以這個問題不再是 100% 有效,但答案仍然很有趣。

再次查看AppleMozillaMozilla文檔,該功能似乎僅限於處理字符串鍵/值對。

一種解決方法是在存儲對象之前對其進行字符串化,然后在檢索時對其進行解析:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('retrievedObject: ', JSON.parse(retrievedObject));

一個變體的小改進:

Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}

由於短路評估,如果key不在 Storage 中, getObject()立即返回null 如果value "" (空字符串; JSON.parse()無法處理),它也不會拋出SyntaxError異常。

您可能會發現使用這些方便的方法擴展 Storage 對象很有用:

Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key) {
    return JSON.parse(this.getItem(key));
}

通過這種方式,您可以獲得您真正想要的功能,即使在 API 下僅支持字符串。

為 Storage 對象創建外觀是一個很棒的解決方案。 這樣,您可以實現自己的getset方法。 對於我的 API,我為 localStorage 創建了一個外觀,然后在設置和獲取時檢查它是否是一個對象。

var data = {
  set: function(key, value) {
    if (!key || !value) {return;}

    if (typeof value === "object") {
      value = JSON.stringify(value);
    }
    localStorage.setItem(key, value);
  },
  get: function(key) {
    var value = localStorage.getItem(key);

    if (!value) {return;}

    // assume it is an object that has been stringified
    if (value[0] === "{") {
      value = JSON.parse(value);
    }

    return value;
  }
}

Stringify 並不能解決所有問題

似乎這里的答案並沒有涵蓋 JavaScript 中所有可能的類型,所以這里有一些關於如何正確處理它們的簡短示例:

// Objects and Arrays:
    var obj = {key: "value"};
    localStorage.object = JSON.stringify(obj);  // Will ignore private members
    obj = JSON.parse(localStorage.object);

// Boolean:
    var bool = false;
    localStorage.bool = bool;
    bool = (localStorage.bool === "true");

// Numbers:
    var num = 42;
    localStorage.num = num;
    num = +localStorage.num;    // Short for "num = parseFloat(localStorage.num);"

// Dates:
    var date = Date.now();
    localStorage.date = date;
    date = new Date(parseInt(localStorage.date));

// Regular expressions:
    var regex = /^No\.[\d]*$/i;     // Usage example: "No.42".match(regex);
    localStorage.regex = regex;
    var components = localStorage.regex.match("^/(.*)/([a-z]*)$");
    regex = new RegExp(components[1], components[2]);

// Functions (not recommended):
    function func() {}

    localStorage.func = func;
    eval(localStorage.func);      // Recreates the function with the name "func"

我不建議存儲函數,因為eval()是邪惡的,可能會導致有關安全、優化和調試的問題。

一般來說, eval()永遠不應該在 JavaScript 代碼中使用。

私人會員

使用JSON.stringify()存儲對象的問題是,這個函數不能序列化私有成員。

這個問題可以通過覆蓋.toString()方法(在 Web 存儲中存儲數據時隱式調用)來解決:

// Object with private and public members:
    function MyClass(privateContent, publicContent) {
        var privateMember = privateContent || "defaultPrivateValue";
        this.publicMember = publicContent  || "defaultPublicValue";

        this.toString = function() {
            return '{"private": "' + privateMember + '", "public": "' + this.publicMember + '"}';
        };
    }
    MyClass.fromString = function(serialisedString) {
        var properties = JSON.parse(serialisedString || "{}");
        return new MyClass(properties.private, properties.public);
    };

// Storing:
    var obj = new MyClass("invisible", "visible");
    localStorage.object = obj;

// Loading:
    obj = MyClass.fromString(localStorage.object);

循環引用

stringify無法處理的另一個問題是循環引用:

var obj = {};
obj["circular"] = obj;
localStorage.object = JSON.stringify(obj);  // Fails

在這個例子中, JSON.stringify()將拋出一個TypeError "Converting circular structure to JSON"

如果應該支持存儲循環引用,可以使用JSON.stringify()的第二個參數:

var obj = {id: 1, sub: {}};
obj.sub["circular"] = obj;
localStorage.object = JSON.stringify(obj, function(key, value) {
    if(key == 'circular') {
        return "$ref" + value.id + "$";
    } else {
        return value;
    }
});

但是,找到存儲循環引用的有效解決方案在很大程度上取決於需要解決的任務,並且恢復此類數據也並非易事。

Stack Overflow 上已經有一些關於處理這個問題的問題: Stringify (convert to JSON) a JavaScript object with circular reference

有一個很棒的庫包含許多解決方案,因此它甚至支持稱為jStorage的舊瀏覽器

你可以設置一個對象

$.jStorage.set(key, value)

並輕松檢索

value = $.jStorage.get(key)
value = $.jStorage.get(key, "default value")

我在點擊另一個已關閉的帖子后到達此帖子 - 標題為“如何在本地存儲中存儲數組?”。 這很好,除了兩個線程實際上都沒有提供關於如何在 localStorage 中維護數組的完整答案 - 但是我已經設法根據兩個線程中包含的信息制定了一個解決方案。

因此,如果其他人希望能夠在數組中推送/彈出/移動項目,並且他們希望將該數組存儲在 localStorage 或實際上是 sessionStorage 中,那么您可以:

Storage.prototype.getArray = function(arrayName) {
  var thisArray = [];
  var fetchArrayObject = this.getItem(arrayName);
  if (typeof fetchArrayObject !== 'undefined') {
    if (fetchArrayObject !== null) { thisArray = JSON.parse(fetchArrayObject); }
  }
  return thisArray;
}

Storage.prototype.pushArrayItem = function(arrayName,arrayItem) {
  var existingArray = this.getArray(arrayName);
  existingArray.push(arrayItem);
  this.setItem(arrayName,JSON.stringify(existingArray));
}

Storage.prototype.popArrayItem = function(arrayName) {
  var arrayItem = {};
  var existingArray = this.getArray(arrayName);
  if (existingArray.length > 0) {
    arrayItem = existingArray.pop();
    this.setItem(arrayName,JSON.stringify(existingArray));
  }
  return arrayItem;
}

Storage.prototype.shiftArrayItem = function(arrayName) {
  var arrayItem = {};
  var existingArray = this.getArray(arrayName);
  if (existingArray.length > 0) {
    arrayItem = existingArray.shift();
    this.setItem(arrayName,JSON.stringify(existingArray));
  }
  return arrayItem;
}

Storage.prototype.unshiftArrayItem = function(arrayName,arrayItem) {
  var existingArray = this.getArray(arrayName);
  existingArray.unshift(arrayItem);
  this.setItem(arrayName,JSON.stringify(existingArray));
}

Storage.prototype.deleteArray = function(arrayName) {
  this.removeItem(arrayName);
}

示例用法 - 在 localStorage 數組中存儲簡單字符串:

localStorage.pushArrayItem('myArray','item one');
localStorage.pushArrayItem('myArray','item two');

示例用法 - 在 sessionStorage 數組中存儲對象:

var item1 = {}; item1.name = 'fred'; item1.age = 48;
sessionStorage.pushArrayItem('myArray',item1);

var item2 = {}; item2.name = 'dave'; item2.age = 22;
sessionStorage.pushArrayItem('myArray',item2);

操作數組的常用方法:

.pushArrayItem(arrayName,arrayItem); -> adds an element onto end of named array
.unshiftArrayItem(arrayName,arrayItem); -> adds an element onto front of named array
.popArrayItem(arrayName); -> removes & returns last array element
.shiftArrayItem(arrayName); -> removes & returns first array element
.getArray(arrayName); -> returns entire array
.deleteArray(arrayName); -> removes entire array from storage

使用JSON對象進行本地存儲:

//組

var m={name:'Hero',Title:'developer'};
localStorage.setItem('us', JSON.stringify(m));

//得到

var gm =JSON.parse(localStorage.getItem('us'));
console.log(gm.name);

//迭代所有本地存儲鍵和值

for (var i = 0, len = localStorage.length; i < len; ++i) {
  console.log(localStorage.getItem(localStorage.key(i)));
}

//刪除

localStorage.removeItem('us');
delete window.localStorage["us"];

理論上,可以使用函數存儲對象:

function store (a)
{
  var c = {f: {}, d: {}};
  for (var k in a)
  {
    if (a.hasOwnProperty(k) && typeof a[k] === 'function')
    {
      c.f[k] = encodeURIComponent(a[k]);
    }
  }

  c.d = a;
  var data = JSON.stringify(c);
  window.localStorage.setItem('CODE', data);
}

function restore ()
{
  var data = window.localStorage.getItem('CODE');
  data = JSON.parse(data);
  var b = data.d;

  for (var k in data.f)
  {
    if (data.f.hasOwnProperty(k))
    {
      b[k] = eval("(" + decodeURIComponent(data.f[k]) + ")");
    }
  }

  return b;
}

但是,函數序列化/反序列化是不可靠的,因為它是依賴於實現的

您還可以覆蓋默認的Storage setItem(key,value)getItem(key)方法,以像處理任何其他數據類型一樣處理對象/數組。 這樣,您可以像往常一樣簡單地調用localStorage.setItem(key,value)localStorage.getItem(key)

我沒有對此進行廣泛的測試,但是對於我一直在修補的一個小項目,它似乎可以正常工作。

Storage.prototype._setItem = Storage.prototype.setItem;
Storage.prototype.setItem = function(key, value)
{
  this._setItem(key, JSON.stringify(value));
}

Storage.prototype._getItem = Storage.prototype.getItem;
Storage.prototype.getItem = function(key)
{  
  try
  {
    return JSON.parse(this._getItem(key));
  }
  catch(e)
  {
    return this._getItem(key);
  }
}

建議對這里討論的許多特性使用抽象庫,以及更好的兼容性。 有很多選擇:

您可以使用localDataStorage透明地存儲 JavaScript 數據類型(Array、Boolean、Date、Float、Integer、String 和 Object)。 它還提供輕量級的數據混淆,自動壓縮字符串,促進鍵(名稱)查詢和(鍵)值查詢,並通過為鍵加前綴來幫助在同一域內強制執行分段共享存儲。

[免責聲明] 我是該實用程序的作者 [/DISCLAIMER]

例子:

localDataStorage.set( 'key1', 'Belgian' )
localDataStorage.set( 'key2', 1200.0047 )
localDataStorage.set( 'key3', true )
localDataStorage.set( 'key4', { 'RSK' : [1,'3',5,'7',9] } )
localDataStorage.set( 'key5', null )

localDataStorage.get( 'key1' )  // -->   'Belgian'
localDataStorage.get( 'key2' )  // -->   1200.0047
localDataStorage.get( 'key3' )  // -->   true
localDataStorage.get( 'key4' )  // -->   Object {RSK: Array(5)}
localDataStorage.get( 'key5' )  // -->   null

如您所見,原始值受到尊重。

您不能存儲沒有字符串格式的鍵值。

LocalStorage僅支持鍵/值的字符串格式。

這就是為什么您應該將數據轉換為字符串,無論它是數組還是對象。

要將數據存儲在 localStorage 中,首先使用 JSON.stringify() 方法對其進行字符串化。

var myObj = [{name:"test", time:"Date 2017-02-03T08:38:04.449Z"}];
localStorage.setItem('item', JSON.stringify(myObj));

然后當你想檢索數據時,你需要再次將字符串解析為對象。

var getObj = JSON.parse(localStorage.getItem('item'));

更好的是,將函數設置為localStorage的 setter和getter,這樣,您將可以更好地控制並且不必重復JSON解析等等。 它甚至可以順利處理您的(“”)空字符串鍵/數據大小寫。

function setItemInStorage(dataKey, data){
    localStorage.setItem(dataKey, JSON.stringify(data));
}

function getItemFromStorage(dataKey){
    var data = localStorage.getItem(dataKey);
    return data? JSON.parse(data): null ;
}

setItemInStorage('user', { name:'tony stark' });
getItemFromStorage('user'); /* return {name:'tony stark'} */

我修改了投票最多的答案之一。 我喜歡單一功能而不是2(如果不需要)。

Storage.prototype.object = function(key, val) {
    if ( typeof val === "undefined" ) {
        var value = this.getItem(key);
        return value ? JSON.parse(value) : null;
    } else {
        this.setItem(key, JSON.stringify(val));
    }
}

localStorage.object("test", {a : 1}); //set value
localStorage.object("test"); //get value

另外,如果未設置任何值,則返回null而不是false false具有某些含義, null沒有含義。

您可以使用ejson將對象存儲為字符串。

EJSON 是 JSON 的擴展,支持更多類型。 它支持所有 JSON 安全類型,以及:

所有 EJSON 序列化也是有效的 JSON。 例如,帶有日期和二進制緩沖區的對象將在 EJSON 中序列化為:

 { "d": {"$date": 1358205756553}, "b": {"$binary": "c3VyZS4="} }

這是我使用 ejson 的 localStorage 包裝器

https://github.com/UziTech/storage.js

我在包裝器中添加了一些類型,包括正則表達式和函數

@Guria的答案的改進:

Storage.prototype.setObject = function (key, value) {
    this.setItem(key, JSON.stringify(value));
};


Storage.prototype.getObject = function (key) {
    var value = this.getItem(key);
    try {
        return JSON.parse(value);
    }
    catch(err) {
        console.log("JSON parse failed for lookup of ", key, "\n error was: ", err);
        return null;
    }
};

另一種選擇是使用現有的插件。

例如, persisto是一個開源項目,它為 localStorage/sessionStorage 提供了一個簡單的接口,並自動化了表單字段(輸入、單選按鈕和復選框)的持久性。

持久功能

(免責聲明:我是作者。)

對於願意設置和獲取類型化屬性的 TypeScript 用戶:

/**
 * Silly wrapper to be able to type the storage keys
 */
export class TypedStorage<T> {

    public removeItem(key: keyof T): void {
        localStorage.removeItem(key);
    }

    public getItem<K extends keyof T>(key: K): T[K] | null {
        const data: string | null =  localStorage.getItem(key);
        return JSON.parse(data);
    }

    public setItem<K extends keyof T>(key: K, value: T[K]): void {
        const data: string = JSON.stringify(value);
        localStorage.setItem(key, data);
    }
}

示例用法

// write an interface for the storage
interface MyStore {
   age: number,
   name: string,
   address: {city:string}
}

const storage: TypedStorage<MyStore> = new TypedStorage<MyStore>();

storage.setItem("wrong key", ""); // error unknown key
storage.setItem("age", "hello"); // error, age should be number
storage.setItem("address", {city:"Here"}); // ok

const address: {city:string} = storage.getItem("address");

https://github.com/adrianmay/rhaboo是一個 localStorage 糖層,可讓您編寫如下內容:

var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);
store.write('somethingfancy', {
  one: ['man', 'went'],
  2: 'mow',
  went: [  2, { mow: ['a', 'meadow' ] }, {}  ]
});
store.somethingfancy.went[1].mow.write(1, 'lawn');

它不使用 JSON.stringify/parse ,因為這在大對象上會不准確且速度慢。 相反,每個終端值都有自己的 localStorage 條目。

您可能會猜到我可能與 rhaboo 有關。

localStorage.setItem('obj',JSON.stringify({name:'Akash'})); // Set Object in localStorage
localStorage.getItem('obj'); // Get Object from localStorage

sessionStorage.setItem('obj',JSON.stringify({name:'Akash'})); // Set Object in sessionStorage
sessionStorage.getItem('obj'); // Get Object from sessionStorage

我制作了另一個只有 20 行代碼的簡約包裝器,以允許像應有的那樣使用它:

localStorage.set('myKey',{a:[1,2,5], b: 'ok'});
localStorage.has('myKey');   // --> true
localStorage.get('myKey');   // --> {a:[1,2,5], b: 'ok'}
localStorage.keys();         // --> ['myKey']
localStorage.remove('myKey');

https://github.com/zevero/simpleWebstorage

一個使用localStorage跟蹤來自聯系人的消息的庫的小示例:

// This class is supposed to be used to keep a track of received message per contacts.
// You have only four methods:

// 1 - Tells you if you can use this library or not...
function isLocalStorageSupported(){
    if(typeof(Storage) !== "undefined" && window['localStorage'] != null ) {
         return true;
     } else {
         return false;
     }
 }

// 2 - Give the list of contacts, a contact is created when you store the first message
 function getContacts(){
    var result = new Array();
    for ( var i = 0, len = localStorage.length; i < len; ++i ) {
        result.push(localStorage.key(i));
    }
    return result;
 }

 // 3 - store a message for a contact
 function storeMessage(contact, message){
    var allMessages;
    var currentMessages = localStorage.getItem(contact);
    if(currentMessages == null){
        var newList = new Array();
        newList.push(message);
        currentMessages = JSON.stringify(newList);
    }
    else
    {
        var currentList =JSON.parse(currentMessages);
        currentList.push(message);
        currentMessages = JSON.stringify(currentList);
    }
    localStorage.setItem(contact, currentMessages);
 }

 // 4 - read the messages of a contact
 function readMessages(contact){

    var result = new Array();
    var currentMessages = localStorage.getItem(contact);

    if(currentMessages != null){
        result =JSON.parse(currentMessages);
    }
    return result;
 }

這是danott 發布的代碼的一些擴展版本:

它還將從 localstorage 中實現一個刪除值,並展示如何添加一個 Getter 和 Setter 層,而不是,

localstorage.setItem(preview, true)

你可以寫

config.preview = true

好的,開始了:

var PT=Storage.prototype

if (typeof PT._setItem >='u')
  PT._setItem = PT.setItem;
PT.setItem = function(key, value)
{
  if (typeof value >='u') //..undefined
    this.removeItem(key)
  else
    this._setItem(key, JSON.stringify(value));
}

if (typeof PT._getItem >='u')
  PT._getItem = PT.getItem;
PT.getItem = function(key)
{
  var ItemData = this._getItem(key)
  try
  {
    return JSON.parse(ItemData);
  }
  catch(e)
  {
    return ItemData;
  }
}

// Aliases for localStorage.set/getItem
get = localStorage.getItem.bind(localStorage)
set = localStorage.setItem.bind(localStorage)

// Create ConfigWrapperObject
var config = {}

// Helper to create getter & setter
function configCreate(PropToAdd){
    Object.defineProperty( config, PropToAdd, {
      get: function ()    { return (get(PropToAdd)    )},
      set: function (val) {         set(PropToAdd, val)}
    })
}
//------------------------------

// Usage Part
// Create properties
configCreate('preview')
configCreate('notification')
//...

// Configuration Data transfer
// Set
config.preview = true

// Get
config.preview

// Delete
config.preview = undefined

好吧,您可以使用.bind(...)別名部分。 但是,我只是把它放進去,因為知道這一點真的很好。 我花了幾個小時來找出為什么一個簡單的get = localStorage.getItem; 不工作。

我做了一個不會破壞現有存儲對象的東西,而是創建了一個包裝器,這樣你就可以做你想做的事了。 結果是一個普通對象,沒有方法,可以像任何對象一樣訪問。

我做的東西。

如果您希望 1 localStorage屬性具有魔力:

var prop = ObjectStorage(localStorage, 'prop');

如果你需要幾個:

var storage = ObjectStorage(localStorage, ['prop', 'more', 'props']);

您對propstorage的對象所做的一切都會自動保存到localStorage中。 你總是在玩一個真實的對象,所以你可以做這樣的事情:

storage.data.list.push('more data');
storage.another.list.splice(1, 2, {another: 'object'});

並且被跟蹤對象的每個新對象都將被自動跟蹤。

最大的缺點:它依賴於Object.observe() ,因此它對瀏覽器的支持非常有限。 而且它看起來不會很快出現在 Firefox 或 Edge 上。

看看這個

假設您有一個稱為電影的以下數組:

var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown", 
              "Kill Bill", "Death Proof", "Inglourious Basterds"];

使用字符串化功能,可以使用以下語法將電影數組轉換為字符串:

localStorage.setItem("quentinTarantino", JSON.stringify(movies));

請注意,我的數據存儲在名為quentinTarantino的密鑰下。

檢索數據

var retrievedData = localStorage.getItem("quentinTarantino");

要將字符串從字符串轉換回對象,請使用JSON解析函數:

var movies2 = JSON.parse(retrievedData);

您可以在電影上調用所有數組方法2

我找到了一種使它與具有循環引用的對象一起工作的方法。

讓我們用循環引用創建一個對象。

obj = {
    L: {
        L: { v: 'lorem' },
        R: { v: 'ipsum' }
    },
    R: {
        L: { v: 'dolor' },
        R: {
            L: { v: 'sit' },
            R: { v: 'amet' }
        }
    }
}
obj.R.L.uncle = obj.L;
obj.R.R.uncle = obj.L;
obj.R.R.L.uncle = obj.R.L;
obj.R.R.R.uncle = obj.R.L;
obj.L.L.uncle = obj.R;
obj.L.R.uncle = obj.R;

由於循環引用,我們不能在這里做JSON.stringify

圓形大叔

LOCALSTORAGE.CYCLICJSON具有.stringify.parse就像普通的JSON一樣,但適用於具有循環引用的對象。 (“Works”意味着 parse(stringify(obj)) 和 obj 是深度相等的,並且具有相同的“內部相等”集)

但我們可以只使用快捷方式:

LOCALSTORAGE.setObject('latinUncles', obj)
recovered = LOCALSTORAGE.getObject('latinUncles')

那么, recovered將與 obj “相同”,在以下意義上:

[
obj.L.L.v === recovered.L.L.v,
obj.L.R.v === recovered.L.R.v,
obj.R.L.v === recovered.R.L.v,
obj.R.R.L.v === recovered.R.R.L.v,
obj.R.R.R.v === recovered.R.R.R.v,
obj.R.L.uncle === obj.L,
obj.R.R.uncle === obj.L,
obj.R.R.L.uncle === obj.R.L,
obj.R.R.R.uncle === obj.R.L,
obj.L.L.uncle === obj.R,
obj.L.R.uncle === obj.R,
recovered.R.L.uncle === recovered.L,
recovered.R.R.uncle === recovered.L,
recovered.R.R.L.uncle === recovered.R.L,
recovered.R.R.R.uncle === recovered.R.L,
recovered.L.L.uncle === recovered.R,
recovered.L.R.uncle === recovered.R
]

這是LOCALSTORAGE的實現

 LOCALSTORAGE = (function(){ "use strict"; var ignore = [Boolean, Date, Number, RegExp, String]; function primitive(item){ if (typeof item === 'object'){ if (item === null) { return true; } for (var i=0; i<ignore.length; i++){ if (item instanceof ignore[i]) { return true; } } return false; } else { return true; } } function infant(value){ return Array.isArray(value) ? [] : {}; } function decycleIntoForest(object, replacer) { if (typeof replacer !== 'function'){ replacer = function(x){ return x; } } object = replacer(object); if (primitive(object)) return object; var objects = [object]; var forest = [infant(object)]; var bucket = new WeakMap(); // bucket = inverse of objects bucket.set(object, 0); function addToBucket(obj){ var result = objects.length; objects.push(obj); bucket.set(obj, result); return result; } function isInBucket(obj){ return bucket.has(obj); } function processNode(source, target){ Object.keys(source).forEach(function(key){ var value = replacer(source[key]); if (primitive(value)){ target[key] = {value: value}; } else { var ptr; if (isInBucket(value)){ ptr = bucket.get(value); } else { ptr = addToBucket(value); var newTree = infant(value); forest.push(newTree); processNode(value, newTree); } target[key] = {pointer: ptr}; } }); } processNode(object, forest[0]); return forest; }; function deForestIntoCycle(forest) { var objects = []; var objectRequested = []; var todo = []; function processTree(idx) { if (idx in objects) return objects[idx]; if (objectRequested[idx]) return null; objectRequested[idx] = true; var tree = forest[idx]; var node = Array.isArray(tree) ? [] : {}; for (var key in tree) { var o = tree[key]; if ('pointer' in o) { var ptr = o.pointer; var value = processTree(ptr); if (value === null) { todo.push({ node: node, key: key, idx: ptr }); } else { node[key] = value; } } else { if ('value' in o) { node[key] = o.value; } else { throw new Error('unexpected') } } } objects[idx] = node; return node; } var result = processTree(0); for (var i = 0; i < todo.length; i++) { var item = todo[i]; item.node[item.key] = objects[item.idx]; } return result; }; var console = { log: function(x){ var the = document.getElementById('the'); the.textContent = the.textContent + '\n' + x; }, delimiter: function(){ var the = document.getElementById('the'); the.textContent = the.textContent + '\n*******************************************'; } } function logCyclicObjectToConsole(root) { var cycleFree = decycleIntoForest(root); var shown = cycleFree.map(function(tree, idx) { return false; }); var indentIncrement = 4; function showItem(nodeSlot, indent, label) { var leadingSpaces = ' '.repeat(indent); var leadingSpacesPlus = ' '.repeat(indent + indentIncrement); if (shown[nodeSlot]) { console.log(leadingSpaces + label + ' ... see above (object #' + nodeSlot + ')'); } else { console.log(leadingSpaces + label + ' object#' + nodeSlot); var tree = cycleFree[nodeSlot]; shown[nodeSlot] = true; Object.keys(tree).forEach(function(key) { var entry = tree[key]; if ('value' in entry) { console.log(leadingSpacesPlus + key + ": " + entry.value); } else { if ('pointer' in entry) { showItem(entry.pointer, indent + indentIncrement, key); } } }); } } console.delimiter(); showItem(0, 0, 'root'); }; function stringify(obj){ return JSON.stringify(decycleIntoForest(obj)); } function parse(str){ return deForestIntoCycle(JSON.parse(str)); } var CYCLICJSON = { decycleIntoForest: decycleIntoForest, deForestIntoCycle : deForestIntoCycle, logCyclicObjectToConsole: logCyclicObjectToConsole, stringify : stringify, parse : parse } function setObject(name, object){ var str = stringify(object); localStorage.setItem(name, str); } function getObject(name){ var str = localStorage.getItem(name); if (str===null) return null; return parse(str); } return { CYCLICJSON : CYCLICJSON, setObject : setObject, getObject : getObject } })(); obj = { L: { L: { v: 'lorem' }, R: { v: 'ipsum' } }, R: { L: { v: 'dolor' }, R: { L: { v: 'sit' }, R: { v: 'amet' } } } } obj.RLuncle = obj.L; obj.RRuncle = obj.L; obj.RRLuncle = obj.RL; obj.RRRuncle = obj.RL; obj.LLuncle = obj.R; obj.LRuncle = obj.R; // LOCALSTORAGE.setObject('latinUncles', obj) // recovered = LOCALSTORAGE.getObject('latinUncles') // localStorage not available inside fiddle ): LOCALSTORAGE.CYCLICJSON.logCyclicObjectToConsole(obj) putIntoLS = LOCALSTORAGE.CYCLICJSON.stringify(obj); recovered = LOCALSTORAGE.CYCLICJSON.parse(putIntoLS); LOCALSTORAGE.CYCLICJSON.logCyclicObjectToConsole(recovered); var the = document.getElementById('the'); the.textContent = the.textContent + '\n\n' + JSON.stringify( [ obj.LLv === recovered.LLv, obj.LRv === recovered.LRv, obj.RLv === recovered.RLv, obj.RRLv === recovered.RRLv, obj.RRRv === recovered.RRRv, obj.RLuncle === obj.L, obj.RRuncle === obj.L, obj.RRLuncle === obj.RL, obj.RRRuncle === obj.RL, obj.LLuncle === obj.R, obj.LRuncle === obj.R, recovered.RLuncle === recovered.L, recovered.RRuncle === recovered.L, recovered.RRLuncle === recovered.RL, recovered.RRRuncle === recovered.RL, recovered.LLuncle === recovered.R, recovered.LRuncle === recovered.R ] )
 <pre id='the'></pre>

這個問題已經從純 JavaScript 的角度得到了充分的回答,其他人已經注意到localStorage.getItemlocalStorage.setItem都沒有對象的概念——它們只處理字符串和字符串。 這個答案提供了一個 TypeScript 友好的解決方案,它結合了其他人純 JavaScript 解決方案中的建議

打字稿 4.2.3

Storage.prototype.setObject = function (key: string, value: unknown) {
  this.setItem(key, JSON.stringify(value));
};

Storage.prototype.getObject = function (key: string) {
  const value = this.getItem(key);
  if (!value) {
    return null;
  }

  return JSON.parse(value);
};

declare global {
  interface Storage {
    setObject: (key: string, value: unknown) => void;
    getObject: (key: string) => unknown;
  }
}

用法

localStorage.setObject('ages', [23, 18, 33, 22, 58]);
localStorage.getObject('ages');

解釋

我們在Storage原型上聲明了setObjectgetObject函數localStorage就是這種類型的一個實例。 除了getObject中的 null 處理之外,沒有什么特別需要注意的。 由於getItem可以返回null ,我們必須提前退出,因為對null值調用JSON.parse會引發運行時異常。

Storage原型上聲明函數后,我們將它們的類型定義包含在全局命名空間中的Storage類型上。

注意:如果我們用箭頭函數定義這些函數,我們需要假設我們調用的存儲對象總是localStorage ,這可能不是真的。 例如,上面的代碼也會為sessionStorage添加setObjectgetObject支持。

我想將JavaScript對象存儲在HTML5 localStorage ,但是我的對象顯然正在轉換為字符串。

我可以使用localStorage存儲和檢索原始JavaScript類型和數組,但是對象似乎無法正常工作。 應該嗎

這是我的代碼:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };
console.log('typeof testObject: ' + typeof testObject);
console.log('testObject properties:');
for (var prop in testObject) {
    console.log('  ' + prop + ': ' + testObject[prop]);
}

// Put the object into storage
localStorage.setItem('testObject', testObject);

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('typeof retrievedObject: ' + typeof retrievedObject);
console.log('Value of retrievedObject: ' + retrievedObject);

控制台輸出為

typeof testObject: object
testObject properties:
  one: 1
  two: 2
  three: 3
typeof retrievedObject: string
Value of retrievedObject: [object Object]

在我看來, setItem方法在存儲輸入之前將輸入轉換為字符串。

我在Safari,Chrome和Firefox中看到了這種現象,因此我認為這是我對HTML5 Web存儲規范的誤解,而不是瀏覽器特定的錯誤或限制。

我試圖弄清http://www.w3.org/TR/html5/infrastructure.html中描述的結構化克隆算法。 我不完全理解這是什么意思,但是也許我的問題與我的對象的屬性不可枚舉有關(???)

有一個簡單的解決方法嗎?


更新:W3C最終改變了對結構化克隆規范的想法,並決定更改規范以匹配實現。 參見https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111 因此,此問題不再100%有效,但答案可能仍然很有趣。

Localstorage只能存儲鍵和值都必須為string的鍵-值對。 但是,您可以通過將對象序列化為JSON字符串,然后在檢索它們時將它們反序列化為JS對象來存儲對象。

例如:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// JSON.stringify turns a JS object into a JSON string, thus we can store it
localStorage.setItem('testObject', JSON.stringify(testObject));

// After we recieve a JSON string we can parse it into a JS object using JSON.parse
var jsObject = JSON.parse(localStorage.getItem('testObject')); 

請注意,這將刪除已建立的原型鏈。 最好通過示例顯示:

 function testObject () { this.one = 1; this.two = 2; this.three = 3; } testObject.prototype.hi = 'hi'; var testObject1 = new testObject(); // logs the string hi, derived from prototype console.log(testObject1.hi); // the prototype of testObject1 is testObject.prototype console.log(Object.getPrototypeOf(testObject1)); // stringify and parse the js object, will result in a normal JS object var parsedObject = JSON.parse(JSON.stringify(testObject1)); // the newly created object now has Object.prototype as its prototype console.log(Object.getPrototypeOf(parsedObject) === Object.prototype); // no longer is testObject the prototype console.log(Object.getPrototypeOf(parsedObject) === testObject.prototype); // thus we cannot longer access the hi property since this was on the prototype console.log(parsedObject.hi); // undefined 

我有這個JS對象 *我想將其存儲在HTML5本地存儲中

   todosList = [
    { id: 0, text: "My todo", finished: false },
    { id: 1, text: "My first todo", finished: false },
    { id: 2, text: "My second todo", finished: false },
    { id: 3, text: "My third todo", finished: false },
    { id: 4, text: "My 4 todo", finished: false },
    { id: 5, text: "My 5 todo", finished: false },
    { id: 6, text: "My 6 todo", finished: false },
    { id: 7, text: "My 7 todo", finished: false },
    { id: 8, text: "My 8 todo", finished: false },
    { id: 9, text: "My 9 todo", finished: false }
];

我可以在HTML5本地存儲以這種方式, 存儲這個由透過JSON.stringify

localStorage.setItem("todosObject", JSON.stringify(todosList));

現在,我可以通過JSON.parsing從本地存儲獲取此對象。

todosList1 = JSON.parse(localStorage.getItem("todosObject"));
console.log(todosList1);

循環引用

在這個答案中,我專注於具有循環引用的純數據對象(沒有函數等),並開發了 maja和 mathheadinclouds提到的想法(我使用他的測試用例,我的代碼要短幾倍)。

實際上,我們可以使用帶有適當替換器的JSON.stringify - 如果源對象包含對某個對象的多重引用,或者包含循環引用,那么我們通過特殊的路徑字符串(類似於JSONPath )引用它。

 // JSON.strigify replacer for objects with circ ref function refReplacer() { let m = new Map(), v = new Map(), init = null; return function(field, value) { let p = m.get(this) + (Array.isArray(this) ? `[${field}]` : '.' + field); let isComplex = value === Object(value) if (isComplex) m.set(value, p); let pp = v.get(value)||''; let path = p.replace(/undefined\.\.?/, ''); let val = pp ? `#REF:${pp[0] == '[' ? '$':'$.'}${pp}` : value; !init ? (init=value) : (val===init ? val="#REF:$" : 0); if(!pp && isComplex) v.set(value, path); return val; } } // --------------- // TEST // --------------- // Generate obj with duplicate/circular references let obj = { L: { L: { v: 'lorem' }, R: { v: 'ipsum' } }, R: { L: { v: 'dolor' }, R: { L: { v: 'sit' }, R: { v: 'amet' } } } } obj.RLuncle = obj.L; obj.RRuncle = obj.L; obj.RRLuncle = obj.RL; obj.RRRuncle = obj.RL; obj.LLuncle = obj.R; obj.LRuncle = obj.R; testObject = obj; let json = JSON.stringify(testObject, refReplacer(), 4); console.log("Test Object\n", testObject); console.log("JSON with JSONpath references\n", json);

使用類似 JSONpath 的引用解析此類 JSON 內容:

 // Parse JSON content with JSONpath references to object function parseRefJSON(json) { let objToPath = new Map(); let pathToObj = new Map(); let o = JSON.parse(json); let traverse = (parent, field) => { let obj = parent; let path = '#REF:$'; if (field !== undefined) { obj = parent[field]; path = objToPath.get(parent) + (Array.isArray(parent) ? `[${field}]` : `${field ? '.' + field : ''}`); } objToPath.set(obj, path); pathToObj.set(path, obj); let ref = pathToObj.get(obj); if (ref) parent[field] = ref; for (let f in obj) if (obj === Object(obj)) traverse(obj, f); } traverse(o); return o; } // --------------- // TEST 1 // --------------- let json = ` { "L": { "L": { "v": "lorem", "uncle": { "L": { "v": "dolor", "uncle": "#REF:$.L" }, "R": { "L": { "v": "sit", "uncle": "#REF:$.LLuncle.L" }, "R": { "v": "amet", "uncle": "#REF:$.LLuncle.L" }, "uncle": "#REF:$.L" } } }, "R": { "v": "ipsum", "uncle": "#REF:$.LLuncle" } }, "R": "#REF:$.LLuncle" }`; let testObject = parseRefJSON(json); console.log("Test Object\n", testObject); // --------------- // TEST 2 // --------------- console.log('Tests from mathheadinclouds answer: '); let recovered = testObject; let obj = { // Original object L: { L: { v: 'lorem' }, R: { v: 'ipsum' } }, R: { L: { v: 'dolor' }, R: { L: { v: 'sit' }, R: { v: 'amet' } } } } obj.RLuncle = obj.L; obj.RRuncle = obj.L; obj.RRLuncle = obj.RL; obj.RRRuncle = obj.RL; obj.LLuncle = obj.R; obj.LRuncle = obj.R; [ obj.LLv === recovered.LLv, obj.LRv === recovered.LRv, obj.RLv === recovered.RLv, obj.RRLv === recovered.RRLv, obj.RRRv === recovered.RRRv, obj.RLuncle === obj.L, obj.RRuncle === obj.L, obj.RRLuncle === obj.RL, obj.RRRuncle === obj.RL, obj.LLuncle === obj.R, obj.LRuncle === obj.R, recovered.RLuncle === recovered.L, recovered.RRuncle === recovered.L, recovered.RRLuncle === recovered.RL, recovered.RRRuncle === recovered.RL, recovered.LLuncle === recovered.R, recovered.LRuncle === recovered.R ].forEach(x => console.log('test pass: ' + x));

要將生成的 JSON 內容加載/保存到存儲中,請使用以下代碼:

localStorage.myObject = JSON.stringify(testObject, refReplacer());  // Save
testObject = parseRefJSON(localStorage.myObject);                   // Load

我建議使用Jackson-js 它是一個基於裝飾器處理對象的序列化和反序列化同時保留其結構的庫。

該庫處理所有缺陷,例如循環引用、屬性別名等。

使用 @JsonProperty() 和 @JsonClassType() 裝飾器簡單地描述你的類。

使用以下方法序列化您的對象:

const objectMapper = new ObjectMapper();
localstore.setItem(key, objectMapper.stringify<yourObjectType>(yourObject));

如需更詳細的解釋,請在此處查看我的答案:

打字稿對象序列化?

Jackson-js 教程在這里:

Jackson-js:強大的 JavaScript 裝飾器,可將對象序列化/反序列化為 JSON,反之亦然(第 1 部分)

從答案看,似乎有很多方法可以存儲JavaScript對象。

您可以設置關鍵字: store ,語言: javascript ,排序方式: 'Most Star'

嘗試使用此GitHub鏈接,您將在頂部獲得當前最多的選擇。

localStorage.setItem('user', JSON.stringify(user));

然后從存儲中檢索它並再次轉換為對象:

var user = JSON.parse(localStorage.getItem('user'));

If we need to delete all entries of the store we can simply do:

localStorage.clear();

遍歷本地存儲

var retrievedData = localStorage.getItem("MyCart");                 

retrievedData.forEach(function (item) {
   console.log(item.itemid);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM