The toJSON function is not being invoked when inside a nested array

Currently, I am immersed in a typescript project and utilizing the toJSON and fromJSON methods to effectively parse my objects.

A peculiar issue has arisen when employing JSON.stringify() on one of my classes, as it neglects to invoke the toJSON methods of the enclosed parameters.

Let me provide an overview of my classes:

class TFClass {
   ...

   toJSON(): ITFSerialized {
      console.log('not printing')
      ...
   }

}

class ConfigClass {
   transfer_functions: TFClass[];
   ...
   toJSON(): IConfigSerialized {
      return Object.assign({}, this, {
         transfer_functions: this.transfer_functions,
      });
   }

}

Upon calling

JSON.stringify(<ConfigClass>obj)
, the transfer_functions variable is considered as TFClass[] leading to the failure to enter the toJSON method of TFClass.

Should the transfer_functions be a singular instance of TFClass, instead of an array, then it would successfully access its respective toJSON method.

What modifications can I implement to rectify this issue?

Answer №1

Remember to add the reviver class as the second parameter in your JSON.parse function. This ensures that the toJSON method is correctly invoked.

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

Is there a way to iterate through an object while capturing the index of each element and then saving it into an array?

After attempting the following code, I am only receiving a single value as output. Object.keys(yelpResults).map((key) => { return setRestaurantIndexes(restaurantIndexes.concat(key)); }); ...

Click to Rotate Angular Chevron

Is it possible to animate the rotation of a chevron icon from left-facing to right-facing using Angular? CSS: .rotate-chevron { transition: .1s linear; } HTML: <button [class.button-open]="!slideOpen" [class.button-close]="slideOpe ...

Ways to retrieve information from MongoDB

How can I retrieve data from a JSON file using mongoshell? I am trying to fetch the data based on policyID. For example, in the JSON file provided, the PolicyID is 3148. I have attempted various commands but I keep getting 0 rows fetched. db.GeneralLiab ...

The flow union type operates smoothly without any errors occurring

In the code snippet below, I have defined a type 'Something' which can have three possible values: 'A', 'B', or 'C'. The function 'f' takes an object of type Something as input and returns a string based on ...

What is the significance of `()=>` in JavaScript when using Selenium?

What is the significance of () => in the following sentence? ()=>{Object.defineProperties(navigator,{webdriver:{get:()=>false}})} I have only seen this syntax in JavaScript and it seems to be used for configuring page evaluation with Selenium. T ...

Jackson never misses an opportunity to create an instance of an abstract base class

Having trouble with deserializing subclasses using Jackson and @JsonTypeInfo. I've defined a set of classes, but Jackson keeps trying to instantiate the abstract base class Communication which results in failure. public class PartnerCommunication { ...

Animate scrolling to a specific div using JavaScript

I am working on a PhoneGap application where I need to scroll to a specific <div> element when opening an HTML page. Currently, I have managed to achieve this using jQuery with the following script: <script> $(document).delegate('.ui-page ...

Troubleshooting: Issues with PHP script and JSON response connectivity

I am in the process of developing a form that allows users to upload images and other data. My aim is for this form to provide JSON validation or success responses through the AJAX success function. However, I have encountered an issue where the PHP scrip ...

How can you access AngularJS scope using Playwright after migrating from Protractor?

I'm encountering a minor (hopefully) issue. For personal reasons, I need to transition from using Protractor to Playwright. Initially, everything was smooth sailing as I migrated numerous steps without any hitches. However, I've hit a roadblock w ...

Creating a Zero to Many Relationship in Prisma: A Step-by-Step Guide for Establishing a (0

While following the Prisma.io documentation, I did not come across any information regarding zero to many relationships. Currently, I am working on developing a daily nutrition system. In this system, I have a model called InfoNutriDay where I intend for ...

Differences in Performance Between jQuery data() and Regular Objects

I'm currently exploring the most efficient way to bind data for an object using jQuery data versus using a traditional object setup. I'm working on establishing a model for my app, and here is the code for the object: var PersonData = function ( ...

Is there a universal framework for PHP and JavaScript commands?

Looking for frameworks that handle PHP <=> JS (AKA "AJAX") communication with all the necessary boilerplate code included to make development smoother. Are there any options worth considering? I know there are libraries out there, but most I've ...

Ways to resolve encoded titles in Youtube API search results

I am currently utilizing the youtube-search 1.1.4 package to search for videos. However, I am encountering an issue where the titles of the results are encoded with &amp; or &#39; instead of simply & and ' and so forth. For instance, an e ...

Utilizing AngularJS to implement a typeahead feature that interacts with a

Currently using AngularJS in conjunction with C# webapi. I'm working on creating an input control that utilizes typeahead to display returned data as the user types. Below is how I have set up the typeahead: HTML: <input type="text" name="uNa ...

Modify the text on a button in ReactJS upon clicking

I am trying to change the text of a button when it is pressed. My goal is to achieve something similar to this example: https://codepen.io/gaearon/pen/xEmzGg?editors=0010, but I am having trouble getting my code to work (I'm new at this). class Obje ...

What's the best way to add animation to the send icon while hovering over the button?

<div class="text-center"> <button [disabled]="btnStatus" class="btn btn-secondary buttonSend" type="submit"> <div [hidden]="btnStatus"> Send Message&nbsp;&nbs ...

Infer the types and flatten arrays within arrays

I am currently working on creating a custom function in typescript that can flatten nested arrays efficiently. My current implementation is as follows: function flattenArrayByKey<T, TProp extends keyof T>(array: T[], prop: TProp): T[TProp] { re ...

The rendering of graphs in FusionCharts is experiencing delays particularly in Internet Explorer, with Chrome performing more efficiently in comparison

I am currently utilizing FusionCharts to generate and display graphs. My requirement is to load over 60 graphs on a single page. Upon testing the page loading in Internet Explorer 11, it is taking approximately 5 minutes. However, when using Google Chrom ...

Click to solve the equation

I want to build a basic HTML page with three input variables (A,B,C). After the user inputs these values, they will click "calculate", and JavaScript will execute the following equations: ((A + B)/2) * 3 = X and (C * 2) = Y The results will be displaye ...

Can you explain the distinction between the onclick(function(){}) and on('click',function(){}) functions in jQuery?

My goal is to dynamically load pages into a specific div using ajax. Here's my HTML code: <ul id="nav" class="nav" style="font-size:12px;"> <li><a href="#" id="m_blink">Tab1</a></li> <li><a href="#" id= ...