Strange behavior of the .hasOwnProperty method

When attempting to instantiate Typescript objects from JSON data received over HTTP, I began considering using the for..in loop along with .hasOwnProperty():

class User {
    private name: string;
    private age: number;

    constructor(data: JSON) {
        console.log('on constructor\ndata', data);

        for (var key in data) {
            console.log('key:', key);
            if (User.hasOwnProperty(key)) {
                console.log('User has key:', key);
                this[key] = data[key];
            }
        }
    }

    displayInfo(): string{
        return JSON.stringify(this);
    }
}

let button = document.createElement('button');
button.textContent = "Test";
button.onclick = () => {
    try{
        let json = JSON.parse('{"name": "Zorro","age": "24"}');
        let usr = new User(json);
        console.log(usr.displayInfo());
    }catch (error){
        alert(error);
    }

}

document.body.appendChild(button);

However, when utilizing similar code in my project, it fails due to the fact that the compiled JS code does not recognize the private TS variables, resulting in hasOwnProperty always returning false.

Interestingly, when testing this code on the Typescript Playground, the console output shows unexpected behavior:

on constructor
data Object {name: "Zorro", age: "24"}
key: name
User has key: name
key: age
{"name":"Zorro"}

This unexpected behavior includes recognizing the first key and initializing the new User instance with the corresponding JSON value, but failing to do the same for the second key. Can anyone explain why this discrepancy occurs?

Answer №1

It was highlighted in the feedback that using this.hasOwnProperty is more appropriate than using User.hasOwnProperty. Additionally, it's important to note that the code provided is flawed because the property declarations within the class do not actually create unique properties on the object unless they are initialized.

So why did the name key trigger a response? The User object functions as a constructor for your class, and functions inherently possess a name property:

function fn() { }
console.log(fn.name); // outputs 'fn'

However, keep in mind that they do not possess an age property.

Answer №2

If you wish to create instances of User from plain JavaScript objects, your constructor should appear as follows:

constructor(data: any) {
    this.name = data.name;
    this.age = data.age;
}

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

Transform the Json file into GraphJSON format for easy importing into Titan database

In my search for a solution to convert JSON files into GraphJSON graphs, I stumbled upon the GraphJSON Reader and Writer Library. One thing that confuses me is whether I can directly read from the path where a JSON file is stored and transform it into a g ...

The maximum JSON length property limit was exceeded in the Ajax POST data in a JavaScript file

I'm encountering an issue when trying to send a large amount of data from a .js file to a .cs file through an ajax call. The error message I'm receiving is: "Error during serialization or deserialization using the JSON JavaScriptSerializer. The ...

Steps to Decode JSON in C#

I have limited experience in c# programming, but I am well-versed in Object-Oriented Programming with PHP and Java. In my current c# code, I am working with a HTTP web response that returns a JSON object. While I have researched various articles and Micros ...

Angular with NX has encountered a project extension that has an invalid name

I am currently using Angular in conjunction with nx. Whenever I attempt to execute the command nx serve todos, I encounter the following error: Project extension with invalid name found The project I am working on is named: todos. To create the todos app ...

Utilizing a nested interface in Typescript allows for creating more complex and

My current interface is structured like this: export interface Foo { data?: Foo; bar?: boolean; } Depending on the scenario, data is used as foo.data.bar or foo.bar. However, when implementing the above interface, I encounter the error message: Prope ...

Dealing with JSON data in the format of `(Object object)` requires a specific approach

I originally encountered object object when attempting to display JSON API data in HTML. I then used keyvalue in *ngFor which allowed me to display the object, but I am wondering how I can access and display the entire JSON data? Here are the relevant cod ...

The order of serialization for JsonPropertyName in .NET Core 3's System.Text.Json.Serialization

While I made the transition to .NET Core 3, I decided to switch from using Newtonsoft.Json serialization to System.Text.Json.Serialization. One feature that I particularly liked and want to continue using is the JsonPropertyName attribute. In the previous ...

What is the proper way to define the type when passing a function as a component prop, with or without parameters?

import { dehydrate, HydrationBoundary } from '@tanstack/react-query'; import getQueryClient from '@/lib/react-query/getQueryClient'; export async function RQBoundary<T>({ children, queryKey, fn, }: { children: React.Reac ...

modify web API response type

I am currently developing a web API project and I need to customize the JSON type being returned. My aim is to return two arrays with a specific format as outlined below: Snippet from my controller public IHttpActionResult GetNOX(){ ------- ...

What is the best way to extract all ID, Name values, and locations from my JSON object and store them in an

I am working with a JSON object named 'tabledata' array. Let's say I want to iterate through all the objects inside it and extract the ID values, so the output would be 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. I also need to access other key-value pai ...

The Standalone Component does not appear for debugging in webpack:source when utilizing an incompatible version of Node

I have developed two components: However, after running ng serve, I am only able to see one component in the source of the Chrome browser: How can I troubleshoot this standalone component? My breakpoints are not being hit in VS Code with the following co ...

Sometimes, a record goes missing from a PHP/JSON array

When calling a PHP script to retrieve results and converting the array into a JavaScript array for a multiple choice quiz, I encountered an issue where certain records were missing unexpectedly. It seems to occur randomly as there is no specific pattern to ...

``There is a possibility for Jackson enum deserialization to assign undesired values to a default "else"

I need help with deserializing XML strings to an enum class called FishType enum class FishType { @JsonProperty("fish-trout") TROUT, @JsonProperty("fish-salmon") SALMON, @JsonProperty("fish-halibut") HALIBUT, . ...

Has the GridToolbarExport functionality in Material UI stopped working since the latest version update to 5.0.0-alpha.37?

I have created a custom toolbar for my Data Grid with the following layout: return ( <GridToolbarContainer> <GridToolbarColumnsButton /> <GridToolbarFilterButton /> <GridToolbarDensitySelector /> <Gr ...

When making an AJAX request, ensure the response is in JSON format with individual properties rather than as a single

Here's an example of an AJAX request with JSON dataType: JavaScript: function checkForNewPosts() { var lastCustomerNewsID = <?php echo $customers_news[0]['id']; ?>; $.ajax({ url: "https://www.example.com/check_for_n ...

Discovering the category for ethereum, provider, and contract

My current interface looks like this: interface IWeb3 { ethereum?: MetaMaskInpageProvider; provider?: any; contract?: any; }; I was able to locate the type for ethereum using import { MetaMaskInpageProvider } from "@metamask/providers", ...

JSON organized in a hierarchical manner with a tree-like structure

I'm working on creating a tree-like JSON structure in Java where there is a parent node with multiple children nodes. While I have made progress on the code, it's not completely successful yet. Here is the desired output: { "name": "Culture" ...

I keep encountering errors whenever I make a request, even though I am correctly inputting the username, key, and issuer details. What could be

{ "errors": { "": [ "A non-empty request body is required." ], "loginRequest": [ "The loginRequest field is required." ] }, "type&quo ...

Troubleshooting PHP for loop issues when working with arrays

I am currently trying to populate a select list with a specific category of options from a json file ('name' in this scenario). I have successfully imported the file and utilized some of the data in other parts of my code (see below), so I believ ...

Unable to pass a component property to a styled Material-UI Button

I have customized a MUI Button: const SecondaryButton = styled(Button)<ButtonProps>(({ theme }) => ({ ... })); export default SecondaryButton; When I try to use it like this: <label htmlFor="contained-button-file"> <input ...