Transform the object into JSON while excluding specific (private) attributes

I recently started using dean edwards base.js for organizing my program into objects. I must say, base.js is truly amazing! But now I have a question that doesn't require prior knowledge of base.js to answer.

Within one of my objects, I have a property called ref which holds a reference to a DOM element. This object needs to be serialized as JSON using JSON.stringify, but the presence of circular structures within DOM elements makes it impossible to convert the object to JSON.

To overcome this issue, I have implemented a method called html() to return the ref property. However, I need ref to be a private property accessible only within the object, ensuring it is not included in the JSON serialization process by stringify.

Can anyone suggest the best approach to achieve this?

Answer №1

JavaScript does not allow private properties, but there is a clever workaround.

If you use JSON.stringify on an object that has a method called toJSON, the method will be automatically called to create a JSON representation of the object. This means you can implement this method yourself to customize the output.

One approach is to create a shallow copy of the object with only the desired properties:

MyConstructor.prototype.toJSON = function() {
    var copy = {},
        exclude = {ref: 1};
    for (var prop in this) {
        if (!exclude[prop]) {
            copy[prop] = this[prop];
        }
    }
    return copy;
};

See DEMO

Alternatively, you could also use a custom replacer function, but it may be more challenging to selectively exclude certain properties like ref:

JSON.stringify(someInstance, function(key, value) {
     if(key !== 'ref') {
         return value;
     }
});

Another DEMO

Answer №2

Check out this example of how to control variable visibility:

function Sample(){
       this.var1 = 'public property'; // This property is accessible from outside the object

       var var2 = 'private property'; // This property is private.

       var self = this;

        this.showVar = function(){
            alert(var2);
            alert(self.var1);
        };
    }

var sampleObj = new Sample();
sampleObj.showVar();

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

Unable to transform JSON Object into a List

Here are the classes I have: public class Datum { public bool Prop1 { get; set; } public bool Prop2 { get; set; } public bool Prop3 { get; set; } public bool Prop4 { get; set; } public bool Prop5 { get; set; } public bool Prop6 { g ...

Leverage the power of React-PDF to smoothly magnify or minimize your

I am working on a ReactJS project where I want to implement zoom in/zoom out functionality. To display PDF files, I am utilizing the react-pdf package in my web application. According to the documentation, there is a scale prop that allows me to adjust the ...

Exploring the possibilities with a Nuxt Site as a foundation

[![enter image description here][1]][1] Exploring the world of nuxt and vue, I aim to build a basic website using vue and then convert it into a static site utilizing: nuxt generate I have successfully accomplished this task with nuxt and vuetify (check ...

Prepare for a thorough cross-referencing session

In my attempt to create a tool with 3 inputs that are interdependent - "Earn %", "Earn $" and "Own Price". Initially, the default value for "Earn percentage" is set at "10", making the initial calculation function as intended. Changing this one value auto ...

Is there a way to embed HTML code within a JavaScript variable?

Embedding HTML code within Java Flow can be quite interesting For instance: Check out this JSFiddle link And here's how you can incorporate it into your script: widget.value += ""; Generating a Pro Roseic Facebook POP-UP Box through Widg ...

Intercepting HTTP requests on specific routes with Angular 4+ using an HTTP Interceptor

I've developed an HTTP_INTERCEPTOR that needs to function on certain routes while excluding others. Initially, it was included in the main app module file. However, after removing it from there and adding it to specific modules, the interceptor conti ...

How to incorporate an image within a div element without reliance on the <img> tag

I am dealing with HTML content <div> <img src="xyz.jpg"> </div> The challenge I am facing is fetching an image in hex format from a web service, converting it to JPEG, and displaying it inside a div. However, the <img src=""> ta ...

Trouble with the datepicker

I tried using the datepicker from and followed its demo, but unfortunately, the datepicker is not showing up on my page. I have gone through everything carefully, but I am unable to identify the reason behind this issue. Could someone please assist me i ...

Receiving HttpPostedFileBase and FormCollection through an Ajax call

I am currently involved in a project where the previous contractor implemented an attachments area on our site. While the functionality works to some extent, there are issues when redirecting back after uploading a file. Additionally, I find it inefficient ...

Explore the HTML code of a webpage to locate a specific attribute, and then identify the parent div element associated with that attribute

Is there a way to identify the parent div ID in javascript or jquery by searching HTML src for a specific attribute or text? Consider the following code snippet: <div id="ad_creative_1" class="ad-div mastad" style="z-index: 1;"> <script>(func ...

Display some text after a delay of 3 seconds using setTimeOut function in ReactJS

When using React JS, I encountered an issue where I am able to display text in the console after 2 seconds, but it is not appearing in the DOM. const items = document.getElementById("items"); const errorDisplay = () => { setTimeout(function () { item ...

Is it possible to include additional transformations to a div element?

Is it possible to add additional rotation to a div that already has a transform applied? For example, can I do the following: <div style="width: 200px; height: 200px; background-color: red; transform: rotateX(90deg) rotateY(10deg)" id="myDiv">< ...

The error message "No native build was found for M2 MacBook" appeared while using npm with Node

I encountered this issue while working on my M2 MacBook, which ran smoothly on my older Intel MacBook. Any insights on what might be causing the problem? Using bun, but even running npm run dev (node 18) results in the same error. The same error has also ...

Creating dynamic VueFire references is a powerful feature that allows for more flexibility and customization

I am currently exploring the creation of refs dynamically: The initial ref I created works fine as it is hardcoded, but the second one does not seem to work because it is dynamic: firebase: function(){ return { categories: db.ref('categ ...

Understanding Date Formats using JSON-lib

Looking at the JSON object below: {"startDate":"30/01/2008","startPeriod":"2008","dboid":"5308204301485575800000","action":"update","grid":"variantAssigGrid","endDate":"30/01/2011","endPeriod":"2011","institution":"5301004301485575300000"} When using JSO ...

Guide on adding a timestamp in an express js application

I attempted to add timestamps to all my requests by using morgan. Here is how I included it: if (process.env.NODE_ENV === 'development') { // Enable logger (morgan) app.use(morgan('common')); } After implementing this, the o ...

Adjust the size of an HTML image for printing using a JavaScript window.print() function

On my website, I have a print option set up where specific elements are hidden using @media. How can I adjust the size of an image within the @media query when my JavaScript print function is triggered? I am able to modify a regular div element easily, but ...

React Resize Detection: Handling Window Resize Events

Is there a more efficient way to listen for the window resize event in react.js without causing multiple callbacks? Perhaps a React-oriented approach (like using a hook) to achieve this? const resizeQuery = () => { console.log("check"); if ( ...

Working with deeply nested JSON arrays in Java

I have a JSON file in the format shown below. { "data":[ { "prjId": 1, "name" : "Forj1", "issue": [ { "id": 00001, "status" : "Closed" ...

Encountering the error message "Jackson: No Object Id found for an instance" while utilizing the @JsonIdentityInfo annotation

My main goal is to avoid recursion in JSON while dealing with the User entity. In order to achieve this, I included the @JsonIdentityInfo annotation in my User class. This worked perfectly for serialization, but during deserialization (when registering a n ...