Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting and getting object to local storage using stringify?

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

like image 801
Sami Avatar asked Aug 21 '12 08:08

Sami


2 Answers

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.

like image 101
Lemex Avatar answered Sep 22 '22 06:09

Lemex


You can't store JavaScript object is localStorage, see this question.

So use your second option. First stringify the object the store it. And later pick it up and parse it to a javascript object.

localStorage.setItem('car',JSON.stringify(car));
carString = localStorage.getItem('car');
car = JSON.parse(carString);
console.log(car.brand); // Skoda
like image 26
fredrik Avatar answered Sep 22 '22 06:09

fredrik