1

I've been working on an application which involved localstorage. I've got an array of deck type objects. The deck object itself contains card type objects. So after looking up on how to use localstorage to store objects, I came up across this SO post:

Storing Objects in HTML5 localStorage

From what I've understood, localstorage stores data only as string, so my deck objects need be converted to a string using JSON.stringify.

However, when I retrieve the objects from localstorage using JSON.parse, I get an object which is not of my original user-defined type, i.e. of deck type.

My question is so: is there a way to retrieve my objects from localstorage as objects of their original type (deck type)? Thank you in advance for your help!

Community
  • 1
  • 1
Hirvesh
  • 7,636
  • 15
  • 59
  • 72

1 Answers1

2

You can use the optional reviver argument to convert them:

var json = '{"decks": [{"cards":[{"id": 1},{"id": 2},{"id": 3}],"id":3},{"cards":[{"id": 4},{"id": 5},{"id": 6}],"id":4}]}';

function Deck( cards, id ) {
    this.cards = cards;
    this.id = id;
}

function Card(id) {
    this.id = id;
}

var decks = JSON.parse(json, function(key, value ) {

    if( key === "decks" ) {
        return value.map( function(deck) {
            return new Deck( deck.cards, deck.id );
        });
    }
    else if( key === "cards" ) {
        return value.map( function( card ) {
            return new Card( card.id );
        });
    }
    else {
        return value;
    }
}).decks;

Then doing:

console.log( decks ) 

Gives the following:

enter image description here

Esailija
  • 138,174
  • 23
  • 272
  • 326