1

I'm using the following Snippet to retrieve an object previously stored in localStorage but for some reason when trying to modify it the object remains unmutable.

This is how I create the object:

if(typeof(Storage) !== "undefined") {
    if(!localStorage.Obj){
        localStorage.Obj = new Object();
    }
    var Obj = localStorage.Obj;

} else {
    if(!$.cookie("Obj")){
        $.cookie("Obj", new Object(), {
            expires : 7, // Days
            domain  : 'localhost:8080',
            secure  : true
        });
    }
    var Obj = $.cookie("Obj");
}

This is where I try to modify the object:

var login = function(email, passwd){

    $.ajax({
        url: "http://127.0.0.1/api/v1/login",
        type: "POST",
        data: { email: email, password: SHA256_hash(passwd), platform: getBrowserName(), osVersion: getOsName()},
        beforeSend: function(xhr){xhr.setRequestHeader('apiKey', "46d1e2f6-cf37-4275-bc1c-d674b12cc9bf");},
        success: function(data, status, xhr){
            Obj["logged_in"] = true;
            Obj["sessionKey"] = data.sessionKey;
            Obj["user_id"] = data.userID;
            Obj["time_format"] = data.timeFormat;
            Obj["first_name"] = data.firstName;
            Obj["last_name"] = data.lastName;
        },
        error: function(data, status, xhr){
            console.log(data);
        }
    });

    if(Obj.logged_in){
        window.location.replace("http://127.0.0.1/users/" + Obj.user_id + "/todos");
    }   
};

I need to point out 3 things:

  • I'm using jQuery
  • The 2 codes are in different files but the loading order is the correct.
  • When using console.log(Obj) I get the following output: "[object Object]"
  • Thanks in advance.
Aitor Martin
  • 724
  • 1
  • 11
  • 26
  • 1
    read up on how localStorage works... it only stores string data. You can convert using JSON.stringify() and JSON.parse() – charlietfl Oct 21 '14 at 21:19
  • I see, as soon as I converted to json String and loaded it, was working perfectly. Please add your answer as official answer so I can set it as correct for the future. – Aitor Martin Oct 21 '14 at 21:26

2 Answers2

1

The underlying problem is that localStorage only stores string data.

For arrays and objects however they can be simply converted to string using JSON.stringify() and when pulling from localStorage the string can be converted to javascript object or array using JSON.parse()

A small library that is helpful is store.js

charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

How do I correctly clone a JavaScript object?

From Pascal's answer: With jQuery, you can shallow copy with:

var copiedObject = jQuery.extend({}, originalObject)

subsequent changes to the copiedObject will not affect the originalObject, and vice versa.

Or to make a deep copy:

var copiedObject = jQuery.extend(true, {}, originalObject)
Community
  • 1
  • 1
Luke Wenke
  • 1,149
  • 2
  • 23
  • 43