Unpacking JSON Objects in Typescript: Working with Private Variables

I have a TypeScript model object called user

export class User {

constructor(
    private _name: string,
    private _email: string
)  {}


public get name():string {
    return this._name;
}

public set name(value:string) {
    this._name = value;
}

get email():string {
    return this._email;
}

set email(value:string) {
    this._email = value;
}

}

The object is stored in local storage using the following code:

let user = new User('myName', 'myEmail');
localStorage.setItem('user', JSON.stringify(user));

After checking the local storage, I found the following string representation of the object:

{"_name":"myName","_email":"myEmail"}

How can I retrieve the user object correctly?

let user: User = JSON.parse(localStorage.getItem('user'));
console.log(user.name); // This logs undefined. It should log 'myName'
console.log(user._name); // Surprisingly, this logs 'myName'. According to TypeScript documentation, this should not work!

I believe the issue has to do with the underscores used when storing the object. How can I properly access the object values?

Answer №1

To properly store and retrieve data in your model, you will need to create serialization and deserialization methods.

class User {
    static public deserialize(serializedData) {
        const {name, email} = JSON.parse(serializedData);
        return new User(name, email);
    }    

    constructor(
        private _name: string,
        private _email: string
    )  {}


    public get name():string {
        return this._name;
    }

    public set name(value:string) {
        this._name = value;
    }

    get email():string {
        return this._email;
    }

    set email(value:string) {
        this._email = value;
    }

    public serialize() {
        return JSON.stringify({name: this.name, email: this.email});
    }

}

let user = new User('myName', 'myEmail');
localStorage.setItem('user', user.serialize());

let storedUser: User = User.deserialize(localStorage.getItem('user'));

Answer №2

After finding inspiration from a helpful response on a different thread, I devised a solution utilizing the capabilities of JSON.parse() and its reviver parameter:

const data = JSON.parse(json, function (key, value) {
    if (key.startsWith('_')) {
        this[key.slice(1)] = value
        return
    }
    return value
})

This approach is also applicable in reverse using JSON.stringify() and its replacer parameter.

It's important to note that an arrow function cannot be used for the callback due to their lack of binding to this.

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

Issue encountered when running a minification build on Angular 5

After successfully updating my Single Page Application (SPA) from Angular 4 to Angular 5 along with all dependencies, everything seemed to be working well. Both the development and production builds were functioning without any errors or warnings. However ...

Troubleshooting a JQuery accordion malfunction within a table

I am populating the data dynamically. However, the Accordion feature is not functioning correctly. JSFiddle link http://jsfiddle.net/aff4vL5g/360/ Please note: I am unable to modify the HTML structure. Current table Desired output The first accordio ...

"Can you provide some information on how to properly parse a JSON string in

<?php if($_SERVER['REQUEST_METHOD']=='GET'){ $id = $_GET['id']; require_once('dbConnect.php'); $sql = "SELECT image FROM images WHERE id = '".$id."'"; $r = mysqli_query($con,$sql); ...

What is the best way to retrieve the checkbox value using AJAX/jQuery with a Spring form?

My form contains a group of checkboxes identified by the path deliveryStatus, like so: <form:checkbox path="deliveryStatus" value="notDelivered"/> <form:checkbox path="deliveryStatus" value="delivered"/> I came across two helpful examples: E ...

Error: The method of promise.then is not recognized as a function

Having an issue with Rxjs v5 while attempting to run http.get requests one after the other in sequential order. The error message received is TypeError: promise.then is not a function. Below is the code snippet in question: var http = require('ht ...

What is the reason behind TypeScript treating numbers as strings when adding them together?

Although TypeScript is strongly typed, can you explain why the code below outputs 12 instead of 3? function add_numbers(a: number, b: number){ return a + b; } var a = '1'; var b = 2; var result = add_numbers(<number><any>a, b) ...

The OnChange event seems to be malfunctioning as it is not being triggered despite other parts of the code functioning properly

Check out the code snippet below: import React, { useState } from "react"; function IP() { const [ipAddress, setIPAddress] = useState(""); const handleInputChange = (event) => { const inputValue = event.target.value; // ...

Following the submission of the ajax form, the page is reloading unexpectedly

I need the voting form on index.php to submit without refreshing the page and display results from an external page within index.php. HTML <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script&g ...

Accessing properties in Angular/TypeScript: extracting values from a partially extended interface

I am fairly new to Angular/TS and I may not have worded this correctly, but I will do my best to explain. I have defined 2 interfaces where one extends the other as shown below: export interface CustomerModel { firstName: string; lastName: string; ...

Transferring a JavaScript element's ID to PHP

Recently, I came across a JavaScript function that automatically updates the date and time for me. I found the script on this URL: http://jsfiddle.net/pLsgJ/1/ setInterval(function() { var currentTime = new Date ( ); var currentHours = curren ...

Using JavaScript to create customized checkboxes is a useful way to

I am looking to develop a JavaScript code that saves all the checkboxes selected by a user. When the user clicks on the finish button, the code should display what they have chosen (text within the label). Admittedly, I am unsure of how to proceed and wou ...

Tips for sending a callback function in Angular following an HTTP request

Currently, I am leveraging an angular controller to make an http post request to my express route. Subsequently, data is dispatched to my Gmail client via nodemailer. Although the $http request functions properly and emails can be received in my Gmail acco ...

Creating dynamic routes for every page fetched from the API in Next.js

Hello everyone, Recently, my journey with NodeJS just commenced and I have been exploring API routes in NextJS as it provides an easy setup and clear visibility of the processes. While I have a grasp on creating basic get requests, I am now intrigued by s ...

Unclear when notifying div content

After creating a PHP page, I encountered an issue while trying to select the inner text of a div and alert it with jQuery. Instead of getting the expected result, it keeps alerting "undefined." What could possibly be causing this? Here is the code snippet ...

Determine whether an object exists within another object and merge its value into the formatted object

When filling out a form, I have a formattedData object that holds a deep copy of the original data object. If a field in the form is changed, I must update the formatted data object with properties from the values object. To simulate this scenario, I crea ...

What's the best way to ensure that the iframe resolution adjusts dynamically to perfectly fit within its container?

iframe-screenshot Displayed in the image are two iframes, but at times I may need to display three. The aim is to ensure that all iframes are responsive within their containers. Below is my existing CSS styling: iframe { width: 100%; height: 1 ...

Struggling to integrate JSON Feed in Full Calendar using CakePHP 3.x

Currently, in my CakePHP 3.1 application, I am able to display events on the calendar by hard coding them. Alternatively, I can also retrieve the events by pasting the array into a jsbin and using the URL from jsbin to fetch the JS file, as per the instruc ...

Avoid parsing HTML tags when retrieving data from Walmart's open APIs

Is it possible to receive a response from Walmart open APIs without escaped HTML tags? For example, when using the search API, here is a sample response: { "query": "ipod", "sort": "relevance", "responseGroup": "base", "totalResults": 257 ...

Rule in ESLint mandating return type for arrow functions

I currently have the following arrow function within my Angular project: this.httpClient.get('url').subscribe((response)=>{ }); It is important to note that ESLint should detect an error in the above code due to not specifying a return type. ...

Verify the presence of an image

I have a code snippet that I use to refresh an image in the browser. However, I want to enhance this code so that it first checks if the image exists before displaying it. If the image does not exist, I want to display the previous version of the picture i ...