The method JSON.stringify is not properly converting the entire object to a string

JSON.stringify(this.workout) is not properly stringifying the entire object. The workout variable is an instance of the Workout class, defined as follows:


export class Workout {
    id: string;
    name: string;
    exercises: Exercise[];
    routine: Routine;
}

The Exercise and Routine classes also contain nested arrays.

The issue lies in the fact that JSON.stringify(this.workout) only returns {"name":"Day 1"}. Can anyone suggest where the problem might be?

Answer №2

After examining the example using plain JS, it is evident that the code functions as intended. It is advisable to carefully review your code and ensure that all objects are properly initialized.

Another approach would be to create a custom toJSON method for any of those classes in order to specify how you want them to be serialized (refer to the example in the class Routine):

class Exercises {
  constructor() {
    this.items = [1, 2, 3];
  }
}

class Routine {
  constructor() {
    this.property = 'DATA';
  }
  
  toJSON() {
    return `ROUTINE = ${ this.property }`;
  }
}

class Workout {
  constructor() {
    this.id = 1;
    this.name = 'Foo';
    this.exercises = new Exercises();
    this.routine = new Routine();
  }
}

const workout = new Workout();

console.log(JSON.stringify(workout, null, 4));
.as-console-wrapper {
  max-height: none !important;
}

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 with the proper functionality of the this.formGroup.updateValueAndValidity() method in Angular 6

Currently, I am facing an issue where I need to add or remove validators in a formGroup's controls based on certain conditions. When I try to update the validators using `formGroup.updateValueAndValidity()` for the entire form, it does not seem to wor ...

Issue with Material UI components: The Select component is collapsed and the autoWidth functionality is not

The Material UI (React) Select component is not expanding in width as expected, even with the autoWidth property. <FormControl margin="dense"> <InputLabel id="prefix-label">Prefix</InputLabel> ...

Is it possible to extract tooltip text from a website using Python and Selenium, specifically when the text is generated by JavaScript?

Can anyone help me retrieve the tooltip text that appears when I hover over the time indicating how long ago a game was played? You can find my summoner profile here. I have noticed that the tooltip text is not visible in the HTML code and suspect it may ...

How to dynamically reduce the number of columns in a textarea using jQuery according to its content

Does anyone know how to make a textarea shrinkwrap the text inside on blur? The default number of columns is 10 or 15 and I want the textarea to adjust its width based on the text content. I have tried the following code: $('textarea').on(&apos ...

Challenges encountered while formatting Json strings for WCF service transmission

I need assistance in connecting a JavaScript application to a WCF service. The WCF Service I have includes the following method: [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFor ...

Having trouble generating a basic TypeScript definition file

I'm having trouble creating a definition file for vue-moment. While it compiles perfectly in IntelliJ, I encounter an issue with vue-cli build: This dependency was not found: * vue-moment in ./src/main.ts In my package.json, I added: "types": "typ ...

Implementing tailwindcss styles in a typescript interface with reactjs

In my code, I have a file named types.ts that defines an interface called CustomCardProps. I pass this interface to the CustomCard component within the home.tsx file. Additionally, I have a folder named constant with an index.ts file where I store values o ...

What is the process for sending an InMemoryUploadedFile to my S3 storage?

My upload form is quite simple and includes an image as a FileField: def post(request): if request.user.is_authenticated(): form_post = PostForm(request.POST or None, request.FILES or None) if form_post.is_valid(): inst ...

What is the reason behind the sorting of sets in jQuery when using the .add() method?

Recently, I encountered an issue while adding multiple DOM objects (SVG elements) totaling around 3000 to an empty jQuery set using the .add() method. The process was taking an unexpectedly long time, causing the UI to freeze while the JavaScript code wa ...

Tips for converting a parent class Sprite into a subclass MySprite in Cocos2d-JS

There is a custom class called MySprite that extends Sprite and includes additional methods. var MySprite = cc.Sprite.extend({ ctor:function(){ this._super(); }, doSomethingStrange:function(){ //meow meow } } ); In the game s ...

How to make an Ajax request in Osclass classified script using a PHP file located in the theme directory?

Currently, I am utilizing the Osclass classified script and attempting to display a message that is returned by an ajax call. Within my theme folder, there is a file called ajax-test.php with the following content: <?php $name = $_GET["name"]; echo "My ...

What is the best way to continuously monitor MongoDB for updates and sync them with my user interface?

Looking to continuously monitor a user's notifications in MongoDB, updating them on specific actions and displaying updates on my React frontend without reloading every time the user logs in. I am currently utilizing Node and Mongoose models for datab ...

What is the best method for incorporating a JavaScript redirect into an Android WebView?

My issue involves loading a page into a webview. Typically, when I use the code webview.loadUrl(url); it functions as expected. The url contains a javascript code that redirects the page. Here is the javascript code: <script type="text/javascript"> ...

`Is there a way to avoid extra re-renders caused by parameters in NextJS?`

I am currently in the process of implementing a standard loading strategy for NextJS applications using framer-motion. function MyApp({ Component, pageProps, router }) { const [isFirstMount, setIsFirstMount] = useState(true); useEffect(() => { ...

Preserving Search and Filter Settings in jQuery Data Tables

I've been working with a datatable and I'm trying to figure out how to keep dropdown filters and search parameters saved when the page is reloaded, just like shown in the screenshot below. However, I also want these parameters to be cleared if th ...

Learn how to upload an image using Vue.js and then trigger a custom method

Greetings! I am a newcomer to Vue.js and I have encountered a problem that I need help with. In my component, there is a hidden input for files. When I click a button, the browser displays a window for importing files from my PC. Once I choose a file, I wa ...

Converting a PHP array into JSON format and displaying the data on a webpage

I'm currently facing an issue with a Json Array. Here is my json data: { "res": ["000000000078", "00000001", "1367771147", "das ist mail text", "000000000080", "00000001", "1367771147", "das ist mail text", "000000000081 ...

Automating radio button selection in AngularJS: Let your code choose the option

In a form with two radio buttons, I am trying to set the first one as the default selection. <input type="radio" name="playlist" ng-value="myCtrl.cleanPlaylist" ng-model="myCtrl.playlistSelected"> Clean <input type="radio" name="playlist" ng-val ...

custom dialog box appears using ajax after successful action

Recently, I created a custom dialog/modal box with the following code: <div id="customdialog" class="modal"> <div class="modal__overlay"></div> <div class="modal__content"> <h2><strong>Hello</strong&g ...

Is it possible to maintain the data types of each individual piece of data when it's divided into an array in

Can the data type of each field be preserved in Javascript after splitting it using the split method? Input: var row = "128, 'FirstName, LastName', null, true, false, null, 'CityName'"; When using the split method, the data type of e ...