Based on your current situation:
You are dealing with a scenario where you receive JSON data from a server which includes names of classes that you will need to use during runtime.
These class names are represented as strings and your goal is to obtain the actual classes they represent.
While utilizing eval
may be an option, it's important to note that using eval
is generally discouraged, especially when dealing with external data sources. This caution is emphasized in resources such as this article from MDN:
eval() is a dangerous function, which executes the code it's passed
with the privileges of the caller. Using eval() on a string
that could be influenced by malicious parties can result
in running harmful code on the user's device within the context of your
webpage / extension. Additionally, third-party code can access the
scope in which eval() was invoked, potentially leading to security vulnerabilities that Function does not have.
If you still opt for using eval, proceed with caution. Alternatively, you can maintain a registry of these classes:
const REGISTRY = {} as { [name: string]: { new(): any };
...
class Home { ... }
REGISTRY["Home"] = Home;
Then, you can do the following:
for (var i = 0; i < arr.length; i++) {
arr[i].root = REGISTRY[arr[i].root];
}
It's also worth mentioning that this approach introduces dependencies between the data received from the server and the client-side application.
Ensuring that the class names provided in your JSON align with the client-side implementations is crucial.
If you decide to rename a class on the client side, remember to make the corresponding update on the server side as well.
Ideally, it's better to focus on returning data exclusively and allow the client-side logic to determine how to handle and locate the necessary classes.