I have a problem with parsing JSON for an array of an object.
I have three JavaScript classes
- Pet
- Cat Extends Pet
- Dog Extends Pet
I want to create an array of Pet objects, then I want to save it in the local browser storage as JSON.
Problem:
When I retrieve JSON and parse it into an array of an object, the prototype of the element changed from Cat or Dog to Object, so when I test
pets[0] instanceof Cat // always false
pets[0] instanceof Dog // always false
Is there a way to save the prototype elements as the original non-object?
Classes:
function Pet(imageUrl, name, soundUrl) {
this.imageUrl = imageUrl;
this.name = name;
this.soundUrl = soundUrl;
this.talk = function() {
};
}
function Cat(imageUrl, name, soundUrl, favoriteFood) {
Pet.apply(this,arguments);
this.favoriteFood=favoriteFood;
}
Cat.prototype=new Pet();
Cat.prototype.constructor = Cat;
function Dog(imageUrl, name, soundUrl, walkingTime) {
Pet.apply(this,arguments);
this.walkingTime=walkingTime;
}
Dog.prototype=new Pet();
Dog.prototype.constructor = Dog;
After creating the array, I have to save it in the local storage of the browser
var pets=[];
var cat = new Cat('imageUrl','name','soundUrl','favoriteFood');
pets.push(cat);
localStorage.setItem('pets', JSON.stringify(pets));
To get an array:
if (localStorage.getItem('pets') !== null)
{
var pets = JSON.parse(localStorage.getItem('pets'));
}