-1

I have an object stored in in local storage which stores more objects, thoes objects lose their methods when stringified and stored,so when I go retrieve I Object.assign them with the new instance of the class that they originally were before being stringified in order to add back the methods using the new instance of that object/class that are lost but for some reason when I check for a method in a method in the task class which is stored in the project object.

           const newMasterObject = new cls.masterObject()
            const storedMasterObject = JSON.parse(localStorage.masterObject)
            // transfering all projects and tasks
            newMasterObject.projects = storedMasterObject.projects.map(project=>{
                const newProject = new cls.Project()
                const newTasks = project.tasks.map(task=>{
                    const variable= Object.assign(new cls.task(),task);
                    return variable
                });
                console.log(newTasks)
                newProject.tasks = newTasks
                console.log(newProject.tasks)
                console.log(newProject)
                return Object.assign(newProject, project)
            })

When I debug it the task object does contain the method (taskHTML) but when I check the newProject with the task array in it which contains that task object the method is gone. However the method is their when I directly check newPorjects.task

here is a photo of everything being logged:enter image description here in the image in the newTasks and newProject.tasks array (which store that a tasks object) the taskHTML method is their but when I check the newProject object and open the tasks array its gone.

1 Answers1

0

Your object's methods disappear because functions are not valid in JSON, so JSON.stringify simply ignores/removes them.

See MDN:

undefined, Function, and Symbol values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to null (when found in an array).

Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34
  • that is why I am an object.assigning them to a new instance of the class to get the methods back, in my console I have gotten them back after assigning them but for some reason it disappears when I check the master object – Hungry_munk Dec 11 '22 at 22:19