JavaScript: utilizing JSON, implementing dynamic methods for creatures, and utilizing closures for encaps

Apologies for the unclear title, but I am unsure where the issue lies.

Therefore, my task is to create a function that generates JavaScript objects from JSON and for fields that start with an underscore, it should create setters and getters.

Here is an example of the test JSON:

{
"_language":null,
"_country":null
}

Below is the function I have written:

function jsonToObject(json){
    return JSON.parse(json,function(key,value){
        if (value && typeof value === 'object') {
            return (function(value){
                var replacement = {};
                for (var k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        //if this is private field 
                        if (k.lastIndexOf("_", 0) === 0){
                            replacement[k]=value[k];
                            var name=k.substring(1);
                            var getName="get"+name.charAt(0).toUpperCase() + name.slice(1);
                            replacement.constructor.prototype[getName]=function(){
                                return this[k];
                            };
                            var setName="set"+name.charAt(0).toUpperCase() + name.slice(1);
                            replacement.constructor.prototype[setName]=function(newValue){
                                this[k]=newValue;
                            };
                        //if this is public field
                        }else{
                            replacement[k]=value[k];
                        }
                    }
                }
                return replacement;
            }(value));
        }
        return value;
    });
}

This is how I tested it:

var test1=jsonToObject(data);
test1.setLanguage("11");
console.log("Point A:"+test1.getLanguage());//ouput 11
var test2=jsonToObject(data);
test2.setLanguage("22");
console.log("Point B:"+test2.getLanguage())//output 22
console.log("Point C:"+test1.getLanguage());//output function (a){this[c]=a}
console.log("Point D:"+test2.getLanguage())//output 22

The issue arises at point C - the expected output should be 11. However, it is currently showing a function...(note: this code has been optimized hence looking obfuscated). Where did I go wrong?

Answer №1

creating setter and getter with duplicate definitions

function convertJsonToObj(jsonData) {
    return JSON.parse(jsonData, function (key, value) {
        if (value && typeof value === 'object') {
            return (function (value) {
                var obj = {};
                for (var prop in value) {
                    if (Object.hasOwnProperty.call(value, prop)) {
                        // Check if property is private
                        if (prop.lastIndexOf("_", 0) === 0) {
                            obj[prop] = value[prop];
                            var propName = prop.substring(1);
                            var getMethodName = "get" + propName.charAt(0).toUpperCase() + propName.slice(1);
                            
                            console.log(obj.constructor.prototype[getMethodName]);
                            
                            if (!/function/.test(typeof obj.constructor.prototype[getMethodName])) {
                                obj.constructor.prototype[getMethodName] = function () {
                                    return this[prop];
                                };
                            }
                            
                            var setMethodName = "set" + propName.charAt(0).toUpperCase() + propName.slice(1);
                            
                            console.log(obj.constructor.prototype[setMethodName]);
                            
                            if (!/function/.test(typeof obj.constructor.prototype[setMethodName])) {
                                obj.constructor.prototype[setMethodName] = function (newValue) {
                                    this[prop] = newValue;
                                };
                            }
                        } else {
                            obj[prop] = value[prop];
                        }
                    }
                }
                return obj;
            }(value));
        }
        
        return 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

Transforming a JSON data stream retrieved from an API using .Net Core 3.0 while maintaining all fields as empty

I am encountering an issue with my simple WPF / .Net Core 3.0 application that makes a GET request to a Web API endpoint: private HttpClient httpClient = new HttpClient(); private async Task GetClients() { var serializer = new DataContractJsonSeriali ...

Refreshing the Date Display with AJAX Response

Within a view, there is a DisplayFor connected to a DateTime field in the Model. After an AJAX call returns a Date to update the field, I am able to convert the AJAX date into a MM/DD/YYYY format. However, using .val to set the DisplayFor does not reflect ...

Incorporating an HTML file into a DIV container while also displaying menu links

I am facing a major challenge with what I recognize as a relatively simple issue for experts. As someone who is still learning, I am struggling to create menu links that load an HTML file into a specific DIV. Despite my efforts, the content keeps loading i ...

Issue with AngularJS: Controller unable to access property of ng-model object

I am looking to create a reusable controller that can be used by multiple views. This controller will essentially serve as a template. The issue I'm facing is with setting up simple validation. The problem lies in the fact that the properties set in ...

Can modifications to the ObjectReader configurations in Jackson ObjectMapper affect the concurrency of multiple threads using the ObjectMapper?

We are working on a Spring-based application and have set up a singleton bean for the Jackson ObjectMapper class. @Bean(name = "jacksonObjectMapper") public ObjectMapper createObjectMapper() { return new ObjectMapper(); } Our task involves creating a g ...

Is it necessary to insert a thread sleep in HtmlUnit before clicking a button?

I have been experimenting with HtmlUnit to extract scores from the BBC Sports website Upon loading the page, it initially displays Premier League scores. To view scores for other leagues, one must use a dropdown menu and click the 'Update' butto ...

LinkedIn Post API: content gets truncated when it includes the characters "()"

I am currently facing a challenge with posting on LinkedIn using their API. The endpoint is https://api.linkedin.com/rest/posts. Everything works smoothly in the integration process until I attempt to post something containing a ( character. Here is an ex ...

Tips for preventing real-time changes to list items using the onchange method

I am facing an issue with a list of items that have an Edit button next to them. When I click the Edit button, a modal pops up displaying the name of the item for editing. However, before clicking the save button, the selected item in the list gets changed ...

Troubleshooting: Difficulty Reading .val() on Elements Selected by Class in jQuery.fn.init(9)

I am facing an issue while trying to retrieve all elements with a specific class name using the code below: productPrices = $('.product-price'); Instead of getting individual values, I am getting the following output: jQuery.fn.init(9) [div. ...

Inserting a large number of records in MySQL using a batch insertion method

Currently, I am facing an issue with inserting multiple records into a MySQL table at once. Just so you know, I am using Node.js along with MySQL (you can find more information about it here: https://www.npmjs.com/package/mysql) Here is what I have been ...

ISerializable, JsonObject, and JSON.NET are essential components in serializing and

Our objects utilize a combination of the ISerializable interface for serialization, along with JsonObject and JsonProperty attributes internally. Here is an example: [JsonObject("Example")] [Serializable] public class Example : ISerializable { ...

Guide to setting up and launching a JavaScript/Vue GitHub repository on your local machine

I have a cloned app located here: cvss-v4-calculator that I want to run locally for debugging with VS Code or a similar tool. However, I'm encountering difficulties in setting it up. I've been attempting to run this as a web page using node.js, b ...

Display a "Loading" image in the gallery before anything else loads

Can a animated loading gif be implemented to load before the gallery images, or would it serve no purpose? The image will be loaded as a background using CSS. <link rel="stylesheet" href="loading.gif" /> Appreciate your help! ...

Using canvas transformation changes the way drawImage is applied

I have been working on a game as a hobby and you can find it at . I have managed to get most aspects of the game working well, such as transformation, selection, movement, and objects. However, there is one particular challenge that I am struggling with. ...

Exploring the depths of Wikipedia through the power of its API

I would like to utilize the query action to search Wikipedia. Currently, I am making use of this specific URL: http://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=apple While this works effectively, my goal is to a ...

Evolution of table size

I have a table that needs to expand smoothly when a certain row is clicked. I want to add a transition effect for a more polished look. Here's my test table: <div ng-app="app"> <table> <thead ng-controller="TestController" ...

WebSocket connection established on port 8888, while the web server is running on port 80 - incompatible to merge the two services

Here is some node.js server-side code that involves watching a file and sending modifications to the browser: var app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs') a ...

What is the correct method for sending a raw string of the content type x-www-form-urlencoded using retrofit?

OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request.Builder requestBuilder = chain.request ...

My large decimal number is unable to be saved by MySQL

My number is 34.59704151614417 When I save it with datatype decimal(16,14), MySQL changes it to 34.59704151614400 because it only saves up to 12 digits after the decimal point. This is my array: Array ( [geometry] => Array ...

napi and SWIG: ThreadSafeFunction only runs in a thread after the thread has finished its execution

Check out this repository I created, where a thread-safe function in a SWIG C++ class is executed using node-addon-api. The thread within the SWIG C++ class is triggered using the napi BlockingCallback as shown below: // C++ thread implementation for (int ...