Using JavaScript to create an object from a JSON data set

Currently, I am working on a TestComplete (UI testing) project that involves JavaScript. In an attempt to store class references in JSON, I have encountered issues with my code not functioning as expected. This has led me to suspect that there may be a misunderstanding regarding how JavaScript manages class references within JSON objects. Below is the snippet of code that outlines my thought process:

class MyClass {
  constructor() {
    this.name = "ClassName";
  }
}

function print_name(str_name) {
  console.log(str_name);
}

let my_json = {
    "keyOne": [
        MyClass
    ]
};

let class_ref = my_json["keyOne"][0];
print_name(class_ref.name);

I am puzzled as to why the print_name function fails to output the "name" property of the MyClass object. Can anyone shed light on why this might be happening?

Answer №1

Yes, there is a reason for that and the correct way to write the code is:

let my_json = {
"keyOne": [
    new MyClass()
    ]
};

Why?

The reason is that you should store an instance of the class, not the class itself. In Javascript, we use the new keyword followed by the constructor function to achieve this.

If you check the code:

typeof MyClass

in the console, you will see function. This syntax comes with ES2015, making it easier to work with many things. Your code is similar to:

function MyClass(){
this.name = "ClassName";
}

This acts as a blueprint, and to create an object, you should use the new keyword followed by the constructor like this:

let mySimpleClass = new MyClass();

If you then console.log:

mySimpleClass.name you will get ClassName.

Note: If you want to convert your my_json variable to actual JSON, use:

JSON.stringify(my_json);

Learn more:

Working with JavaScript Objects

JSON.stringify()

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

Ways to showcase numerous records in Ember.js template using hasMany relationship?

The model I have defined looks something like this: App.Question = DS.Model.extend({ title: DS.attr( 'string' ), answers: DS.hasMany('App.Answer') }); App.Answer = DS.Model.extend({ title: DS.attr( 'string&ap ...

Using Puppeteer to cycle through a CSV file and take a screenshot for each individual row?

I am looking to automate screenshotting URLs from a CSV file using puppeteer, but the current code execution is slow as each request waits for the previous one to finish. const csv = require('csv-parser'); const fs = require('fs'); con ...

"Kindly complete all mandatory fields" - The undisclosed field is preventing me from submitting

I am facing an issue with my WordPress page that has Buddyboss installed along with Elementor pro as the Pagebuilder. The Buddyboss plugin provides Facebook-like functions on the website. While it is easy to comment on posts within the Buddy Boss system, I ...

See-through Windows on Linux (Electron)

When creating a new BrowserWindow in Electron and using the transparent argument set to true, it typically gives the window a transparent background. However, I have found that this is not the case for Linux based on my knowledge. I have also attempted to ...

JavaScript logic for playing the hangman game

I am working on creating a hangman game and I need some guidance on developing the logic. I am new to programming, so I would like to keep it simple by using basic syntax. One thing I'm trying to figure out is how to display dashes (-) that represent ...

The combination of Inline CSS and Bootstrap classes does not seem to be functioning properly

I'm new to web design and currently working on a website project. My concept involves hiding the #login-box when the user clicks on the login button, and displaying another element (.dashboard) in its place. Initially, I set the .dashboard class to ha ...

Troubleshooting problem with JSON decoding in PHP and json_encode

Encountering an issue when parsing JSON received from a PHP backend. In my PHP code, I have an array that I send using json_encode: $result[] = (object) array('src' => "{$mergedFile}", 'thumb_src' => "{$thumb_file}"); echo json_e ...

What is the process for generating a comprehensive HTML table using AngularJS?

I have a set of data that needs to be dynamically loaded into an HTML page. Currently, I am using AngularJS to populate each table on the page. As of now, there are 8 tables in total. My goal is to make the table counts completely dynamic so that I can e ...

What is the correct way to activate buttons within a v-for loop in Vue.js?

My current situation is as follows: https://plnkr.co/edit/LdbVJCuy3oojfyOa2MS7 https://i.sstatic.net/ivWnE.png I am looking to activate the "Press me" buttons when the input changes. At this point, I have a code snippet that can detect when the input h ...

Ways to disable an AJAX loading animation

In my current script, I am loading external content using the following code: <script type="text/javascript"> var http_request = false; function makePOSTRequest(url, parameters) { // Code for making POST request } function alertContents() { ...

AngularJS: Tips for Waiting in the 'Run' Method until Completion

I am facing a simple issue - I want to set up my http calls with an interceptor that will include a token in the headers. The challenge is that the token is received through an http call as well (which should be the initial call), and I'm unsure how t ...

node js retrieves information from the request body

Hey there! I'm diving into the world of Node.js and JavaScript, but I've hit a roadblock. I'm trying to fetch data from a URL using node-fetch, then parse it as JSON. However, I keep running into the issue of getting 'undefined' in ...

Steps to prevent specific links from being clickable in React Native's webview component

In my React Native app, I am utilizing the react-native-webview component to display blog posts. The code I have implemented is straightforward, but my goal is to restrict the webview to only show content from the blog section of the website, preventing us ...

Choose the initial p tag that includes an image, based on the content of another div

I am trying to figure out how to manipulate the code on my website: <div class="the-post-thumbnail"> <img src="" alt="" width="" height="" /> </div> <div class="post-body"> <p><img src="" alt="" width="" height="" ...

The identifier for the $.find control is not defined

My goal is to dynamically generate a control and then modify another control without using post/get queries. For example, I have a button and a label, and I want to change the label's text using AJAX/JavaScript. Here is the code I am using: f ...

Tips for expanding a script that relocates a logo into a navigation consisting of several unordered lists

I recently implemented a jQuery script to center a logo within my main navigation bar only when the screen width is above 980 pixels. It was working perfectly fine with a single unordered list, but as soon as I added more unordered lists within the nav, it ...

What is causing Angular services to malfunction when used within setTimeout and setInterval functions?

manage-tasks.component.html <p>manage-tasks works!</p> <form #taskForm="ngForm"> <input type="text" name="task_name" palceholder="Task Name" [(ngModel)]="task_service.selected_task.name& ...

The Angular http.post function seems to be returning null responses consistently, without any actual data being received

When making a post call in Angular using Http.post, I am sending jsonData as a parameter with the following formatted data. However, every time I receive a response as null. Could you please review my code and let me know if there are any mistakes? Here ...

Tips for inserting a hyperlink into a Chakra UI toast

Exploring the integration of Chakra UI within my Next.js project has led me to a curious question: Can Chakra UI toasts accommodate links and styled text? If so, what is the process for implementing these features? ...

Issue with Mouse Hover not functioning properly across various 3D objects

Trying to create a 3D line chart? Check it out Here Currently, the points and lines are working fine. However, I only want to detect mouse hover on the points (spheres) and not on the lines or grid. To achieve this, I have segregated all elements into dif ...