Is there a way to reset an object's prototype in typescript after fetching it from local storage?

In my TypeScript class, there is a method called getTotal() defined on the prototype.

class Score {
    roundOne: any;
    roundTwo: any;
    roundThree: any;
    roundFour: any;
    roundFive: any;
    roundSix: any;
    roundSeven: any;
    getTotal() {
      let total = 0;
      if(!isNaN(parseInt(this.roundOne))) total+=parseInt(this.roundOne);
      if(!isNaN(parseInt(this.roundTwo))) total+=parseInt(this.roundTwo);
      if(!isNaN(parseInt(this.roundThree))) total+=parseInt(this.roundThree);
      if(!isNaN(parseInt(this.roundFour))) total+=parseInt(this.roundFour);
      if(!isNaN(parseInt(this.roundFive))) total+=parseInt(this.roundFive);
      if(!isNaN(parseInt(this.roundSix))) total+=parseInt(this.roundSix);
      if(!isNaN(parseInt(this.roundSeven))) total+=parseInt(this.roundSeven);

      return total;
    }
}

Everything works fine with the method until I store an instance of 'Score' in localStorage and then try to retrieve it. The problem is that the object loses its prototype, resulting in the getTotal() method becoming inaccessible. Apart from changing the structure of my code, I'm wondering if there is a way to reattach or point the objects back to their prototype once retrieved from localStorage. Is there a solution similar to the following:

let scores = JSON.parse(localStorage.getItem('scores'));

scores.forEach(function(score){
  // reattach or point to prototype here
})

Answer №1

When parsing a JSON, it doesn't create instances of classes but rather simple JavaScript objects with the same properties.

There are two main approaches to handling this:
(1) Implement a constructor that can manage the state object:

class Score {
    roundOne: any;
    roundTwo: any;
    ...

    constructor(state: Score) {
        this.roundOne = state.roundOne;
        this.roundTwo = state.roundTwo;
        ...
    }

    getTotal() {
        ...
    }
}

let scores = (JSON.parse(localStorage.getItem('scores')) as Score[])
    .map(score => new Score(score));

It's important to note that even though the type Score is used for the state objects, they simply share the same structure (excluding the method). You can create an interface for this purpose as well:

interface State {
    roundOne: any;
    roundTwo: any;
    ...
}

(2) Alternatively, utilize Object.assign:

let scores = (JSON.parse(localStorage.getItem('scores')) as Score[])
    .map(score => Object.assign(new Score(), score));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

data retrieval not refreshing sorting post construction

My challenge involves fetching data from MongoDB with sorting. While it works perfectly on the development server, it fails to update the data after being built and hosted. import Review from "@/models/review"; import connectdb from "@/util/ ...

Personalize the loading bar using JavaScript

Currently, I am utilizing a basic progress bar from Bootstrap. However, I have the desire to design a custom progress bar similar to this: Unfortunately, I am uncertain about how to create such a unique progress bar. Perhaps there is an existing JavaScri ...

What is the process for incorporating a personalized inputComponent JSX <input /> into a react-phone-number-input PhoneInput component?

Instructions to follow when working with code. react-phone-number-input provides the option for users to replace its default <input /> JSX tag with a custom one, requiring the type React.ForwardRefExoticComponent<React.InputHTMLAttributes<HTML ...

Is it possible to create floating unordered lists using Bootstrap in HTML?

Is there a way to float text left or maintain list order in the HTML code of my page while using a dense CSS from this bootstrap template? For example, I would like my list to remain organized regardless of how many items are added: https://i.sstatic.net ...

Is there a way to use JavaScript or jQuery to identify if Firefox is blocking mixed content

Is there a way to detect when Firefox (or any browser) is blocking mixed content using JavaScript or jQuery? To learn more about Firefox's mixed content blocking feature, visit: The backstory: My company has an external vendor that handles the onli ...

What is the best way to include variable child directives within a parent directive in AngularJS?

Exploring a New Angular Challenge In the current project I am engaged in, I am faced with a unique problem that requires an 'angular way' solution. Despite my best efforts, I seem to be hitting a roadblock every time I attempt to solve it. The ...

What is the best way to display a default image in a kendo grid when the image field is empty?

I am trying to display a default image if the image field is empty. Below is the code for the image field: { field: "Photo", title: "Photo", template: '<img src="#= Photo ? Photo : 'default.jpg' #" alt="image" width="80px" height="80px" ...

How to Retrieve Content from an iFrame Using jQuery?

I am facing a challenge with an HTML form that is directed to an IFRAME upon clicking "submit". The iframe then loads a page after the submission, which indicates whether the user-input data is valid or not. It simply displays on screen as "TRUE" or "FALSE ...

AngularJS does not allow empty spaces in textarea inputs

I am working on a form that includes a textarea element for users to input descriptions, however it does not allow any empty spaces. Users can only input alphanumeric and numeric characters, but no spaces. <textarea class="form-control" rows="4" maxl ...

Hide a div element upon selecting an option from a dropdown menu

On iPhone 6plus and lower, I created a dropdown menu that opens when users click on "jobs" or "contact." However, after clicking on these options, the drop-down menu remains open. How can I make it hide automatically after a list item is clicked at this sp ...

Transmit parameters via onclick event on FullCalendar

I have been utilizing the full calendar feature and it's been functioning properly. However, I am encountering an issue with sending parameters via onclick event. Below is the JavaScript code that I currently have: <script> $(document).ready(fu ...

transformation of categorized unions in software development

Experimenting with routing-controllers and its built-in class-transformer feature, I tried creating an interface for executing a search query based on either a location id or location coordinate. My aim was to utilize a discriminated union as a body parame ...

Tips for utilizing maps in a react component within a Next.js application

I received an array of data from the backend that I need to display on a React component. home.js import Head from "next/head"; import Header from "../src/components/Header"; import * as React from 'react'; import { styled } ...

Dispatching identification to controller after submission

I am encountering an issue with a page that contains the following code: <div class="col-sm-2 displaybutton"> <div data-point-to="displaysHeader"> @using (Html.BeginForm("Administration", "Home", FormMethod.Post)) ...

Transforming an ES6 JSON object into a dictionary: a step-by-step guide

As someone who is new to learning ES6 and JQuery, please forgive me if this question has been asked before (I couldn't find similar ones). Currently, I am working on retrieving data from a JSON file in the following format: { EUR: { code: "EUR" ...

javascript/AngularJS - make elements gradually disappear

I need help implementing a fade effect for an icon in the middle of a picture that indicates scrollability to the user. Currently, when the user scrolls, I can hide the icon but would like to add a nice smooth fade-out effect. Here is the HTML code snippe ...

Capture and store the current ionic toggle status in real-time to send to the database

I have a list of names from the database that I need to display. Each name should have a toggle button associated with it, and when toggled, the value should be posted back to the database. How can I achieve this functionality in an Ionic application while ...

Trapped in a Continuous Observing Loop with MdSnackBar in Angular Material within Angular 2

Whenever my login attempt fails, I want to display a snackbar with the message 'error connecting'. After dismissing the snackbar, I would like the login to be retried after 10 seconds. However, I'm facing an issue where my observable is runn ...

redactor.js: Disable backspace functionality when cursor is at the start of a div-container

Currently, I am working with the redactor.js editor that utilizes editable div containers. A challenge I have encountered is when multiple contenteditable containers are nested; deleting content using the backspace button can inadvertently delete the entir ...

The Express GET route does not support parameters or additional paths

I am facing an issue with making a fetch request when trying to add additional path or parameters... Here is what I want to achieve: const fetchOwnerCardList = () => { fetch("http://localhost:5000/api/card/ownerCards", { method: "GET", header ...