Setting and getting object to local storage using stringify?

Sami picture Sami · Aug 21, 2012 · Viewed 28.9k times · Source

Creating an object called car:

function car(temp){

    this.brand=temp[0];
    this.color=temp[1];
    this.year=temp[2];
}

var temp = ['Skoda', 'Red', '2012'];
car = new car(temp);
  1. Setting object and stringify after reading from localStorage:

    localStorage.setItem('car',car);
    car = localStorage.getItem('car');
    car = JSON.stringify(car);
    

    car after stringify-----------------> [object Object] at file:///android_asset/www/...

  2. Stringify object and Setting object to localStorage after it: localStorage.setItem('car',JSON.stringify(car)); car = localStorage.getItem('car');

car after stringify-----------------> "{\"brand\":\"Skoda\",\"color\":\"Red\",\"year\":\"2012\"}" at file:///android_asset/www/...

Question 1: Why does it make difference what is the order when you stringify the object?

Question 2: Why can't I use stringified object like that:

08-21 11:49:14.860: I/Web Console(9642): car after stringify----------------->     {"brand":"Skoda","color":"Red","year":"2012"}

console.log("car.brand----->" +car.brand); car.name----->undefined

Answer

Lemex picture Lemex · Aug 21, 2012

From my understanding you can't use your stringified object once it's been stringified because it's no longer an object. It's a String.

So when you try to do car.brand on the string there is no property brand.

Personally, good practice in my opinion would be to do.

 function car(temp){
     this.brand=temp[0];
     this.color=temp[1];
     this.year=temp[2];
 }

 var temp = ['Skoda', 'Red', '2012'];
 car = new car(temp);

 localStorage.setItem('car',JSON.stringify(car)); 
 car = localStorage.getItem('car');
 car = JSON.parse(car);

This means the car object is now not a string but an object.

When doing this also write to local storage using stringify and read using parse.