0

im creating in JS a Cart, whitch takes pizzas or salads, or another food products, then i save the cart in localStorage with JSON.stringify. But when i retrieve the cart from JSON.parse, the items are simple Objects, whereas before it was an instance of Pizza, or Salad...etc

The items before:

[Pizza]: {id: 1, name:"Hawaï pizza", ...}
[Pizza]: {id: 2, name:"Fresh Italian pizza", ...}
[Salad]: {id: 3, name:"Chicken Salad", ...}

The items after:

0: {id: 1, name:"Hawaï pizza", ...}
1: {id: 2, name:"Fresh Italian pizza", ...}
2: {id: 3, name:"Chicken Salad", ...}

The problem: I have implemented some methods on each products (like Pizza.getSize() ...etc) that doesnt work after JSON.parse.

How can I retrieve that items with their original Prototypes ? Or is here a trick used to resolve that ?

Thanks

Samir B
  • 152
  • 1
  • 2
  • 13
  • 1
    No real "trick", you need to do the prototype assigning yourself. But to do that, you need to know what type each had before you serialised it. – VLAZ Mar 02 '20 at 11:33
  • 1
    You can't. JSON is a serialized string from the original object, the prototype information is not included. You could add the name of the prototype to the data, that might help to add a correct prototype back to the objects. Notice, that the prototypes have to be methods of an object in order them to be able to be referred with a string (bracket notation actually). – Teemu Mar 02 '20 at 11:33

0 Answers0