Creating a custom toJSON function for a property declared using Object.defineProperty

Let's consider a scenario where we have an object with a specific property that is meant to reference another object, as shown below:

Object.defineProperty(parent, 'child', {
    enumerable: true,
    get: function() { return this._actualChild; },
    set: function(v){
      if(v && typeof v === 'object'){
            this._actualChild = v;
      } else {
        throw new TypeError('child property must be an object!')
      }
    }
  });

Is it possible to customize the behavior of this property when using JSON.stringify(), so that the .child property has its own unique toJSON method?

For example, after initializing the following:

var jill = {id: 3, name: 'Jill'};
parent.child = jill;

If we could somehow define the toJSON for parent.child to only return the id property of the child. This means that JSON.stringify(parent) would output:

{_actualChild: {id: 3, name: 'Jill'}, child: 3}

We can certainly define a toJSON method for the child object itself, but in that case we would get:

{_actualChild: 3, child: 3}

Ideally, I want to separate the property's toJSON method from the actual child object's toJSON method. Is there a way to achieve this?

It would be convenient if we could do something like this:

  Object.defineProperty(o, 'child', {
    enumerable: true,
    get: function() {
      return this._hiddenChild;
    },
    set: function(v){
      if(v && typeof v === 'object'){
            this._hiddenChild = v;
      }
      else {
        throw new TypeError('child property must be an object!')
      }
    },
    toJSON : function() {
      return this._hiddenChild.id;
    }
  });

However, Object.defineProperty does not accept a toJSON descriptor.

Answer №1

Unfortunately, it is not possible to specify stringification behavior for individual properties. Instead, you will have to implement a toJSON method directly on the parent object:

var parent = {};
Object.defineProperty(parent, "child", {…});
parent.child = …;
parent.toJSON = function() {
    return {_actualChild:this.child, child:this.child.id};
};

> JSON.stringify(parent)
{"_actualChild":{"id":3,"name":"Jill"},"child":3}

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

Submitting Files with jQuery AJAX in the ASP.NET MVC Framework

Currently, I am working on an application that requires me to upload a file using AJAX. I have implemented the jQuery.form library for this purpose, but strangely, when the action is triggered, the controller receives an empty list of files. Below is the H ...

How to Properly Page Resources in REST API

Two contrasting approaches to paging with REST are showcased below. Which one is considered more 'correct'? In both examples, the standard Link HTTP header is utilized to include URLs for next, previous, first and last pages. Defining Pages in ...

Unraveling a JSON structure with unspecified keys in the top tier - the ultimate guide

Seeking help to decode JSON data: { "unknown_key1": { "info": "Info text", "text": "More text" }, "unknown_key2": { "info": "Info text", ...

Unable to interpret Python/Django-generated JSON object on client side

I'm encountering an issue while passing a data object from a Python/Django application to the frontend using AJAX in JSON format. Despite everything appearing to be functioning correctly, I am unable to properly parse the JSON object within JavaScript ...

retrieve JSON information using JSONP

Currently, I am working with a URL that returns data in JSON format. Here is the URL: http://10.0.1.11/render?target=threshold(400,test)&from=-1mins&format=json&jsonp=? When I enter this URL into a browser, it displays the following JSON re ...

What is the most efficient way to loop through an array and send each item to a method, ensuring that all methods are executed synchronously?

I need to make a request method call that retrieves its own body as an array, which is one item within another array. To achieve this, I have to iterate over the parent array and pass each of its items to the request method for a new server request. I tr ...

Adjust the FlipClock time based on the attribute value

When setting up multiple FlipClock objects on a page, I need to retrieve an attribute from the HTML element. The specific HTML tag for the clock is: <span class="expire-clock" data-expire="2015-09-22"> Is there a way to access '2015-09-22&apos ...

Experiencing a problem with the localhost connection

I've been trying to work on this issue using React and local host, but it keeps showing the direct file instead of the website. I've been stuck on this problem for the past 3-4 hours and still haven't been able to find a solution. I'm h ...

utilizing a pair of API requests within a personalized Alexa skill

I posted a question about integrating Alexa with the Steam custom skill API here, but I realize it might be too detailed for some to read through. In essence, my main question is: Can you make two separate API calls within the same block of JS code while ...

What is the significance of the statement "What is the meaning of "#include <common>" in Three.js, WebGL, and GLSL?

The Three.js shader example linked here uses a function called rand() with a vec2 input to create random numbers. Interestingly, the function is not defined within the shader code itself. Instead, it appears to be included through the use of #include < ...

Displaying a Google chart with no data using JSON

Recently, I've been tackling the challenge of setting up Google Charts to display data from a local database. After some persistence, I believe I have successfully formatted the JSON output. { "cols": [ { "id": "", ...

The JSON code encountered an unexpected token

My current setup involves using webpack with React to load external data from a static json file. Inside my entry.jsx file, I have the following code: const data = require('../data/data.json'); However, this code results in an error message: ...

Is Volley equipped with built-in support for JSON arguments and string responses?

I am trying to send a JSON payload via a server POST request and receive a string response. After researching extensively, it appears that doing this with the Volley library is not straightforward unless I create a custom request (which I find daunting). ...

Using JavaScript to pre-select a radio button without any user interaction

Is there a way to programmatically set a radio button in a group without physically clicking on the button? I am attempting to open a jQuery page and depending on a stored value, the corresponding radio button should be selected. I have researched similar ...

Using an iframe containing a link to trigger the opening of a colorbox in the

Recently, I encountered a challenge regarding an iframe containing a bar graph. I wanted to achieve that when the graph is clicked, it would open a colorbox with a more detailed graph from the "PARENT" of that iframe. Initially, I managed to get the ifram ...

attempting to communicate with Postman but encountering an error in the process

Upon attempting to send a request through Postman, I encountered an error. Nodemon is operational and the server is active in the terminal. index.server.js file //jshint esversion:6 const express = require("express"); const env = require("d ...

You must use the 'new' keyword to invoke the class constructor NextResponse | Implementing middleware in Next.js | Implementing role-based protection for routes in Next.js |

I've been working on implementing user role-based protected routes in my next.js project using middleware.js, but all of a sudden, I've encountered this issue. I'm not exactly sure why this is happening, so if anyone has a better approach to ...

Creating JSON in Python by combining data from two lists of lists involves merging the elements from both lists into a single JSON format

Having two csv files(semi-colon delimited) with the structure and sample data below: File 1: qid;question 1.0;How can I find specific content 2.0;How do I modify content 2.0;How can I edit items 2.0;I need to change some answers 3.0;How do I troubleshoot ...

Vibrant Flutter image with a splash of color

I am currently working on developing an API that will display product images and colors. The goal is to have the image associated with a specific color appear when the user clicks on the corresponding color button using PageView.builder. I need help creati ...

Explore vue3 components using vue-test-library and universal components

I started creating unit tests for a production app using jest, @testing-library/vue, and supporting libraries. The first test I created is as follows: import vue from "vue"; import { render } from "@testing-library/vue"; import LibBtn f ...