2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Storing Objects in HTML5 localStorage

When i tried to store JavaScript object in HTML5 localStorage. It  is apparently being converted to a string. whereas I can store and retrieve primitive JavaScript types and arrays using localStorage, but objects don"t seem to work. Should they? Below is my code

var testObject = { "cat": 1, "dog": 2, "elephant": 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);


The output is:

typeof testObject: object

testObject properties:

  cat: 1

  dog: 2

  elephant: 3

typeof retrievedObject: string

Value of retrievedObject: [object Object]


Well, i think "setItem" method is converting the input to a string before storing it.

userimage

Extending the Storage object is an awesome solution. For my API, I have created a facade for localStorage and then check if it is an object or not while setting and getting.


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;
  }
}

Answer is