When converting to JSON, objects may sometimes lose their properties

Here is a sample of my class structure:

export class Patient {
constructor(public id: number, public name: string, public location: string, public bedId: number, public severity: string,
public trajectory: number, public vitalSigns: [GraphData[]], public latestReading: GraphData[]){
}
 public get getCombinedVSData(): Array<GraphData>{
    let combinedVitalSigns: GraphData[] = [];
    for (let data of this.vitalSigns){
        combinedVitalSigns.push(data[0]);
    }
    return combinedVitalSigns;
}

}

When I try to print out one of the patients from the service,

console.log(this.patientService.patients[0]);

This is the output I receive:

https://i.sstatic.net/GKdpv.png

For drag and drop functionality in my application, I need to convert the patient object to JSON format:

let jsonData=JSON.stringify(this.patientService.patients[0]);

However, upon converting it back to a JavaScript object and printing it,

console.log(JSON.parse(jsonData));

The resulting output no longer contains the Patient class identifier and the getCombinedVSData getter function.

Is this the expected behavior when working with JSON conversion? How can I ensure that the getter remains intact on the object during JSON transformation? Thank you.

Answer №1

According to the JSON documentation, functions cannot be included in JSON data as valid data types are limited to string, number, object, array, true, false, and null.

To illustrate how methods can be removed from an object using json.stringify() and json.parse(), consider the following example:

var obj = {
  "prop": "value",
  "method": function(num) {
    return num + 1;
  }
};

var json = JSON.stringify(obj);

var new_obj = JSON.parse(json);

Object.keys(new_obj).forEach(function(key){
  console.log(key + " : " + new_obj[key]);
});

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

When attempting to parse JSON using RestSharp, the error message "System.NullReferenceException: Object reference not set to an instance of an object" is displayed

I am currently developing a user interface that allows users to input a stock symbol/ticker and retrieve data on the stock such as open price, high, low, and closing price by clicking a button. The data is retrieved using the Alpha Vantage API. To view an ...

Loop through a non-array or non-object / handling both arrays and non-arrays equally

Sometimes, I find myself needing to handle arrays and single objects in a similar manner. For instance, I may have an object property that can be either an array or just a string (like the scale property): [ { "name": "Experiment type14", "id": ...

Calculating the sum of fields added dynamically using jQuery

I am currently working on a dynamic table where I can add rows dynamically. However, I am facing an issue in including a subtotal at the bottom of the table. This is what I have tried so far: Here is the JavaScript code snippet: $(document).on('chan ...

How can I determine if a URL in react js includes a specific string?

I am working on a project where I need to check if a given URL contains the string youtube using react hooks in React JS. This is what my current code looks like: useEffect(() => { let srcLink = "www.google.com/https://img.youtube.com/vi/h9-qcy3HQn ...

Navigating an array to link values to anchor tags

I'm struggling with an array that contains image file names ["1352.jpg", "1353.jpg", "1354"]. My goal is to loop through this array and generate anchor links for each item separated by commas. I've attempted the following code snippet, but it&apo ...

As my character slides off the moving platform in this exciting Javascript canvas game, my heart

Can anyone help me figure out how to keep my player on the moving platform? I'm not sure if I need to add gravity or something else. I'm still learning the ropes. export function checkTopCollision({ item1, item2 }) { return ( item1.y + item ...

Unable to save the current light/dark mode preference to local storage

Being a beginner in JavaScript, I am currently working on implementing a simple light mode button for my website which defaults to dark mode. The transition between JS/CSS dark and light modes is seamless, giving the site an appealing look when switching t ...

Empty Media Viewer

I am encountering an issue with setting up a code, as it only displays a blank white page. Any suggestions on what might be causing this problem in the setup and assistance in resolving it would be greatly appreciated. <script type="text/javascript ...

Rotate the d3.js datamap by dragging using your cursor

Recently, I created a custom map using datamaps developed by @markmarkoh I'm thrilled with how it turned out, but I am eager to add functionality that allows the map to rotate when dragged with a cursor. My inspiration comes from examples like the on ...

Suggestions for updating ng-repeat variable with autocomplete functionality?

Many thanks to the Stack Overflow community for helping me resolve my previous angularjs and autocomplete issue. Here is the link to the question: Angularjs with jquery auto complete not working However, I am facing a similar problem now within the ng-rep ...

The API for /api/addproducts has been resolved without a response being sent, potentially causing delays in processing requests

A response was not sent for the /api/addproducts API, which can lead to delays in processing requests. Below is the code for the add product API that I have been working on: I've debugged it using the console, but I'm still struggling to find t ...

Sliding in a strange way

Are you experiencing a strange behavior with the slider on your website? When you hover over the image, the caption at the bottom slides up and on mouseout it slides down again. It works perfectly on . However, when navigating to portfolio via the menu on ...

Problems arise when attempting to load a JSON file using the d3 library installed through npm

I recently added d3 through npm. In my package.json file, the dependencies section shows "d3": "^4.11.0". I attempted to load a simple JSON file using the following code: const d3 = require('d3') d3.json('jsonfile.json', (err, data) ...

Dynamic row generation with dropdown menu and data binding

Currently, I am working with a table that dynamically creates rows containing details of uploaded files. Each row includes a dropdown menu for selecting the file type. The issue I am encountering is with the dynamically generated dropdown menus. If I sele ...

Learn how to dynamically pass a click event from a div to a checkbox with delegation

I need assistance with a scenario where clicking on a button within a component triggers another click event on a specific checkbox located in a different div within the same component. Essentially, I want to programmatically simulate a click on the checkb ...

Converting MySQL Bit Type to Swift 3: A Comprehensive Guide

My current database utilizes a Bit type object to represent a boolean variable. https://i.sstatic.net/1qI2j.png However, when attempting to retrieve this data from MySQL to Swift 3, it returns Nil. The PHP file functions correctly as running the PHP code ...

Customizing the appearance of jQuery accordion components

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js" language="javascript"></script> <script type="text/javascript" src="http://www.compactcourse.com/js/accordionNew.js" language="javascript"></script> < ...

Ways to retrieve information from JSON

I am currently trying to access the values of an object that is within an array which is inside another object. The data is structured as follows: [{ "id": "99a4e6ef-68b0-4cdc-8f2f-d0337290a9be", "stock_name": "J ...

Having trouble bringing in icons from the @mui/icons-material library

An error occurs when attempting to run the code. wait - compiling... error - ../../../../../node_modules/@mui/icons-material/esm/utils/createSvgIcon.js:1:0 Module not found: Can't resolve '@mui/material/utils' null Note: @mui/material pack ...

What happens to the code that is situated *after* the closing of the HEAD tag and just before the opening of the BODY tag

I recently came across conflicting information regarding the placement of code between the HTML head and body tags. While it is considered bad practice and outside the spec, I have noticed an intermittent error in our complex code base that may be related ...