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);
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/...
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With