What is the purpose of the JavaScript function <object>.toJSON(...) and how does it impact the object without being explicitly called upon?

Still new to JavaScript, I recently encountered this code snippet. How exactly did the function impact the final result? What confuses me is that the function is defined and immediately called ( pet.toJSON() << Something similar to this ). So how does it actually work? Lastly, what is the specific name of this function or where can I find resources to better understand it? Apologies if these questions seem basic, but your explanation would greatly benefit my learning process. Wishing you a wonderful day!

const pet = {
  name: 'Marek'
}

pet.toJSON = function () {

  return {}
}

console.log(JSON.stringify(pet))   // the result is {}



userSchema.methods.toJSON = function () {
    const user = this
    const userObject = user.toObject()

    delete userObject.password
    delete userObject.tokens

    return userObject
}

Answer №1

What type of JavaScript function is represented by

<object>.<somefunction>
?

It is simply a standard method.

How does it affect the object without being directly called?

It gets invoked indirectly, usually by code that you didn't personally author or are not currently examining.

The inner workings of JSON.stringify involve scanning for a method named toJSON in objects and executing it if found.

Refer to the official documentation on MDN:

If the value has a toJSON() method, it's responsible for determining what data gets serialized.

You can also view the specification (specifically focusing on this section):

  • Locate the toJSON method using Get(value, "toJSON").
  • Handle any exceptions thrown during this process.
  • If toJSON is callable
    • Execute Call(toJSON, value, «key») to manipulate the value.

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

Tips for converting Form Input field data into JSON Format with Jquery Ajax

I need to convert data from the controller into JSON format, but it is currently in string form. Is there a way to achieve this? I tried using headers for passing data in an AJAX call, but it doesn't convert the form field into JSON format. Due to the ...

Mysterious and never-ending loop that seems to loop endlessly and eludes my

My prototype includes a method for adding callbacks: /* * Add a callback function that is invoked on every element submitted and must return a data object. * May be used as well for transmitting static data. * * The callback function is supposed to e ...

Is there a way to conduct a Mongoose query that excludes or ignores specific strings?

I'm struggling to find a concise title, so please suggest ways to make it clearer. Now, onto my question - I need to query phone numbers in my database, but they are stored in two different formats: with dashes and without. For example: {phone: ' ...

Reset preview image upon submission

I have a contact form where I am using the following code to display an uploaded image preview: [file fileuploader filetypes:jpg id:uploader] <img id="preview" src="#" /> <script> var uploader = document.getElementById(&apos ...

While using axios to make a GET request, I encountered errors when checking for .isSuccess in react

const searchInvoiceList = async ( plantLocation: string, invoiceType: string ) => { let dataList: InvoiceData[] = []; await axios .get(`${linkURL}inv/getControlList/${plantLocation}/${invoiceType}`) .then((response) => { dataLis ...

Using HTML5 and an ASP.NET web method to allow for file uploads

My attempt to upload a file to the server using an HTML5 input control with type="file" is not working as expected. Below is the client-side JavaScript code I am using: var fd = new FormData(); fd.append("fileToUpload", document.getElementById(&ap ...

When trying to publish a new post using postman, the content including the title, message, and image is not displaying

I am currently learning how to build a REST API by following a tutorial. Below is an excerpt from my server.js file: import express from 'express'; import compression from 'compression'; import bodyParser from 'body-parser'; ...

What is the best way to target and manipulate the transform property of multiple div elements in JavaScript?

Looking at this code snippet, my goal is to have all the boxes rotate 180deg with a single click, without needing to apply different ID names: function rotateAllBoxes() { var boxes = document.getElementsByClassName("box"); for (var i = 0; i < box ...

Order JSON Array Using LoDash Library

Recently I encountered a JSON array with the following structure: var json = [ { key: 'firstName', value: 'Bill' }, { key: 'lastName', value: 'Mans' }, { key: 'phone', value: '123.456.7890&apo ...

Error in scrolling previews detected in Jssor horizontal template maker

I've been working with Jssor Slider Maker and I'm using the vertical preview template that features two columns on the left side and a maximized image on the right side. After pulling the code from the developers pack, it includes scripts, CSS an ...

Tips for retaining filled data after an incomplete form submission

<html> <head><script type="text/javascript"> function pa(){ var fname = document.getElementById('fname').value; var lname = document.getElementById('lname').value; var email = document. ...

Error occurred while attempting to fetch the associated objects from the Parse.Query

I'm running into an issue with Parse.Query and how to handle the result promise. Here's my current code snippet: var ga = new Parse.Query(Game); ga.include('away_team'); ga.include('home_team'); ga.equalTo("objectId", req.par ...

What is the best approach to setting up dynamic Vue routing?

I am working on implementing dynamic routing for the website that relies on changes in agreements. Here is the path tree I have set up: const routes = [ { path: "/", redirect: "/home", component: DefaultLayou ...

Error when accessing YouTube API Credentials - TypeError occurred: Unable to retrieve property '0' as it is undefined

I have encountered an issue with the YouTube API Browser key. I have two keys at my disposal, one that I created recently and another from a sample project where I obtained the code. The problem arises when I try to use my own key, as it seems to be ineffe ...

using jquery ajax to assign an image to an image control

I am struggling to display an image from a base64 string result using the image control. I tried $('Image1').attr(); but it's not working. Any assistance would be greatly appreciated. $.ajax({ async: false, type: "POST", url: "PostDat ...

Angular: Implementing a Dark and Light Mode Toggle with Bootstrap 4

Looking for suggestions on the most effective way to incorporate dark mode and light mode into my bootstrap 4 (scss) angular application. Since the Angular cli compiles scss files, I'm not keen on the traditional method of using separate css files for ...

Error in Formatting Labels in CSS

I currently have a form with textboxes that include validation. Everything works smoothly when clicking the save button for the first time, but if we fill out the textboxes and then remove the text, an error message is displayed on the textboxes. You can v ...

Embracing the use of paragraph tags within tweets on a webpage

For a project on freecodecamp.com, I created a quote machine where you click a button to get a random quote and then have the option to tweet it using the "Tweet It" button. However, I encountered difficulty in getting the quote to display properly in the ...

Convergence phenomenon in SVG when two distinct paths intersect

Working with individual SVG paths and in need of a mitre effect when there is a path join, which is a new concept for me. The SVG shape resembles a polygon, with each side as its own individual path. Although the sample SVG code provided does not display ...

Encountering the error "ReferenceError: data not defined" while utilizing JSONP in my code

I'm encountering an issue when trying to display JSON data using JSONP. I have a complex JSON file that is being delivered from a different domain via a URL and my expertise in JSON and ajax is limited. After following a tutorial on JSONP at https://l ...