What is the process of converting a string within an array into a class?

I need help figuring out how to convert a string within an array into a class instance. The following code snippet is similar to what I'm working on:

var elements = ["({x: 0, y: 0, width: 100, height: 100})", "({x: 10, y: 10, width: 70, height: 70})"];
for(var i = 0; i < elements.length;i++) {
   var objClass = new window[elements[i]];
   console.log(objClass.width);
}

Answer №1

The syntax you provided in the variable classes doesn't match the requirements of the JSON Syntax, so using JSON.parse() is not a safe option.

Alternatively, you can use the eval() function which is native in JavaScript:

let classes = ["({x: 0, y: 0, width: 100, height: 100})", "({x: 10, y: 10, width: 70, height: 70})"],
    objects = []
objects = classes.map((c)=> eval(c))
console.log(objects)

Note: It is not recommended to use eval() unless you have complete control over the origin of the string, as it could introduce vulnerabilities to your application.

Answer №2

JSON.parse() is a method that can transform a JSON string into an object. An example of this in action:

JSON.parse("{'width':100, 'height':200}")

This code will result in a JavaScript object being returned.

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

First experience with Django Bootstrap Modal Ajax was flawless, but on the second attempt, it was not as successful

I am currently utilizing Django 2.2 in conjunction with Bootstrap. The method implemented is as follows: Triggering the opening of a modal window, User updates the data, User saves the data, Underlying table from where the window originated is updated a ...

Tips on how to select the clicked class within a div using AJAX

Can you please explain how the browser stores content from a div called in ajax? I'm confused about why I can't directly target the content called in ajax and displayed in the browser inspector with jQuery. Also, how can I easily target a class ...

Using Vuex: Delay dispatch of action until websocket response received

Let's look at the given scenario and premises: To populate a chat queue in real time, it is necessary to establish a connection to a websocket, send a message, and then store the data in a websocket store. This store will handle all the websocket sta ...

Setting a specific index in an array of objects in React: A comprehensive guide

I currently have a useState() object structured as follows: const [financeSummary, setFinanceSummary] = useState({ discountRate: 10, financeRate: 10, reinvestRate: 10, inflationRate: 3, singleInvestment: new Array( ...

Insert a fresh row into the gridview using JavaScript

I am working with a grid view where I dynamically add new rows using JavaScript. Each row in the grid view contains an image (addButton), which triggers a specific JavaScript function when clicked. function AddNewRecord(e) { debugger; var hfFirst ...

I keep encountering a syntax error in my AngularJS project - what could be causing this

I'm encountering the following error in my AngularJS project. Can you assist me with resolving it? Error angular.min.js:117Error: [$parse:syntax] http://errors.angularjs.org/1.5.6/$parse/syntax?p0=Shoping&p1=is%20an%20unexpected%20token&p2=8 ...

Using Bootstrap 4 to Filter Cards by Title and Tag

I'm attempting to develop searchable cards using HTML, JavaScript, and Bootstrap 4, but I'm facing issues with my code. My goal is to filter these three cards using a search bar, based on their title (h5.card-title) and tags (a.badge). Below is ...

Delving into the depths of the recursive search for the smallest value

Currently, my objective is to identify the local minima in a random row of an image (which I have achieved), and then locate the local minima within that list. I have formulated the following code to utilize a function for discovering the minimum values ...

How can the values from the scale [-60, -30, -10, 0, 3, 6, 10] be converted to a decimal range of 0-1 through

Thank you for helping me with so many of my issues. <3 I'm certain that someone has already solved this, but I'm unsure of the specific mathematical term (I've attempted reverse interpolation and others, but with no luck) so I am present ...

Preserve HTML element states upon refreshing the page

On my webpage, I have draggable and resizable DIVs that I want to save the state of so they remain the same after a page refresh. This functionality is seen in features like Facebook chat where open windows remain open even after refreshing the page. Can ...

What do I do when I get a "findByIdAndUpdate is not a function" error from my controller after requiring the model

I am currently developing a web application for my company that allows us to access and manage a database of customers and their information using MongoDB, Mongoose, and Express. Our company specializes in reselling used copiers/printers and offering maint ...

Issue with resetting JavaScript input value in onblur event

I have a function where I'm trying to clear the value of an input element, but it's not working as expected. The code looks like this: inputT1.onblur = function () { var pDomain = this.value; $.get("netutil/php/trial500.php", { ...

Object list with dynamic key names

I have implemented a 'meta' modal box using both bootstrap and angularjs. My current goal is to utilize this setup for saving entered details and sending them to the web API that is running behind the scenes. The functionality works perfectly, bu ...

Using jQuery to toggle between two elements and updating the SELECT field

<div class="r_row"> <div class="row field_currency"> <div class="f_row"><label class="" for="currency">Currency</label></div> <div class="r_row"> <select id="currency" name="currency" class=" select ...

Trouble with Bootstrap 5 Dropdown Menu failing to drop down

I am attempting to utilize a dropdown menu on my Wordpress site with Bootstrap, but it is not working as expected. If I manually add the class "show" to my dropdown-menu div, the menu displays, but the button does not function. These are the scripts being ...

Eliminating a row from a numpy array using a specific condition

Given the array below : test = np.array([[1,2,'a'],[4,5,6],[7,'a',9],[10,11,12]]) Is there a way to remove the rows that have the value 'a' in them? Desired outcome : array([[ 4, 5, 6], [10, 11, 12]]) ...

Sort through an array of objects using a different array

I am looking to showcase projects based on specific skills. For instance, if I choose "HTML", I want to see all projects that have "HTML" listed in their array of skills. If I select multiple skills, then only display projects that have those exact skills. ...

Guide on how to display registration form data on the current page as well as on a separate page

I am facing an issue with outputting registration form data to two different pages after successful validation. Specifically, I want the form data to be displayed on both the current page (form.php) and another page (profile.php). Despite my efforts to fin ...

What steps should I follow to enable my bot to generate or duplicate a new voice channel?

I needed my bot to either create a new voice server or clone an existing one. The variable "voic" contains the ID of the voice channel. voic.voiceChannel.clone(undefined, true, false, 'Needed a clone') // example from ...

The Ajax function fails to trigger during the first load of the page

Note: Kindly refer to the update at the end of this question before proceeding. The problem described is specific to IE 11 and emerged after a recent Windows update. Following the installation of 5 updates, including one for IE, I removed the latter hopin ...