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

Guidance on uploading a file with AJAX in PHP following the display of a Sweet Alert

I am currently facing an issue with inserting a file input (images) into my database. When I try to insert it, the value returned is empty. Below is the script I am using: <script> $("#insertform").on('submit',(function(e) { ...

Monitor elements in real-time as they are inserted into the DOM using a Chrome Extension

In the process of developing a Chrome extension, I am tackling the task of removing or hiding specific elements based on their id/class. While accomplishing this after the DOM is loaded poses no issue, it does result in a noticeable "blink" on the page dur ...

Is there a way to seamlessly inject a stylesheet into a React application without causing any flickering or reloading on the website?

In my React application built with next.js, I am fetching a stylesheet via a GET request and appending it to the webpage. However, whenever this stylesheet is loaded in, the elements impacted by it re-render unnecessarily, even if there are no actual chang ...

Change a portion of the CSS background-image URL using vanilla JavaScript for a set of pictures

My current code successfully updates part of an src URL for regular images. let svgz = document.querySelectorAll(".svg"); for (let i = 0; i < svgz.length; i++) { svgz[i].src = svgz[i].src.replace("light", "dark"); } Now, ...

c# - Convert selected items from checked listbox to JSON

Hey there! I have a checked listbox and I'm looking to add the checked items to my List and then serialize them with JSON. For example: public class Customer { public string Name { get; set; } public string Products { get; set; } } List& ...

Why is it that comparing the childNodes of two identical nodes results in false, while comparing their innerHTML yields true?

Currently, I am in the process of developing a simple function in Node.js that compares two DOMs. My goal is to not only identify any differences between them but also pinpoint the exact variance. Interestingly, upon reconstructing identical DOMs using jsd ...

Extracting all the details from JSON to Java POJO classes is proving to be challenging

I am currently utilizing the Jackson parser for JSON parsing. My goal is to extract the "props" from the JSON provided below. I need suggestions on what modifications are necessary in the Java POJO class to retrieve the value of "props". The following is t ...

Tips for triggering an event from a function instead of the window

Everything is functioning as expected, with the event listener successfully capturing the custom event when it is dispatched from the window and listened for as loading, all seems to be working well. const MyLib = mylib(); function mylib() { const re ...

The server is sending unprocessed raw JSON data that Angular is unable to handle

I've been working on accessing data from the server and storing it in $scope.resp, but I'm only seeing raw JSON displayed on the page. Here is the code from routes/addr.js: router.get('/', function(req, res) { var persons = [{add ...

What is the process for adjusting the width of an element using JavaScript?

I have a unique bar with one half red and the other green. I am trying to subtract 1vw from the width of the red section. Unfortunately, using style.width is not yielding the desired result. See below for the code snippet I am currently using: //FIGHT do ...

The decoded data is different from the original get request

Greetings everyone, I am new to Perl but have some experience with other programming languages. Recently, I created a simple code that retrieves a JSON file from the internet for a Telegram bot. However, when I display the data, everything seems fine. But ...

Ajax cannot seem to come to a resolution

After completing my learning on Ajax, I decided to work on a simple project - a port scanner. However, I am facing issues with it as it is not working properly. The only message that pops up is 'Scan started' and I can't figure out what the ...

Is it possible to simultaneously use two $scoped variables within an Angular controller?

Currently, I am developing an angular application that connects to a Rails backend and interacts with the database through API calls to receive JSON objects. My challenge lies in defining multiple scoped variables within a controller. At the moment, I have ...

What is the best configuration to use for successful MapReduce queries in Riak?

While working on a nodejs application with riak / riak-js, I encountered the following issue: Executing this request db.mapreduce .add('logs') .run(); successfully retrieves all 155.000 items stored in the bucket logs along with their IDs ...

Tips for distinguishing individual rows within a table that includes rowspans?

My Vue application calculates a table with rowspans by using an algorithm based on a configuration file. This allows the application to render columns (and maintain their order) dynamically, depending on the calculated result. For example, see the code sn ...

Dynamic table in Vue.js updates with saved data when button is clicked

I am looking for assistance on how to work with two or more parameters using Vue.js. I have a data-saving functionality where three inputs are used and the data is saved to a table upon button click. There is an $.ajax() function involved, but I need help ...

What is the best way to display a div box only when a user checks a checkbox for the first time out of a group of checkboxes, which could be 7 or more, and then hide the

Is there a way to make a div box appear when the user checks any of the first checkboxes? I have attempted using the following codes: JQ Codes: $('#checkbox').change(function() { if ($(this:first).is(':checked')) { cons ...

Transitioning to Meteor and React or Immigrating to Meteor

Are there any available resources specifically designed for Meteor that can assist with loading large assets (ranging from 20MB to 80MB) primarily for offline use? Currently, I am working on a project using Vanilla JS on the client side, but I am contempl ...

Retrieving a result from a function call is a fundamental aspect of programming

I have a scenario where I am initiating a call from a controller within AngularJS. This call passes some data to a service in order to receive a response that needs to be conditionally checked. Controller patents.forEach(function(item){ // The "patents" ...

"Exploring ways to reattempt a route request upon encountering the $stateNotFound event within AngularUI Router

Managing a large AngularJS application can be quite challenging when it comes to splitting it into functional modules. Currently, all the modules are loaded on the initial page load as they are bundled into a single JavaScript file. However, I am looking t ...