Below is a JSON that I am trying to access.
{
"orders": {
"errorData": {
"errors": {
"error": [
{
"code": "ERROR_01",
"description": "API service is down"
}
]
}
},
"status": "fail"
}
}
To make accessing the JSON easier and more maintainable, I want to declare constants to refer to its keys since the structure might change in future. For example, if I want to access the value of the "status" key, I could use a constant to represent it. Let's call the entire JSON object 'data'. In TypeScript, this could look like:
public static STATUS : string = "data["orders"]["status"]";
var status_value = STATUS;
The issue here is that this code simply assigns the string version of STATUS to the variable "status_value", without actually evaluating it. One option would be to use eval on STATUS, but that's not recommended. I've heard about a loop solution, but it seems too complex for my current needs considering that I'll be dealing with this JSON in multiple places in my Angular 2 app which involves lots of backend calls and JSON parsing.
Would it make sense to create a function that handles the loop logic as a constant and then call it whenever needed? Any suggestions from JavaScript pros would be greatly appreciated, especially since I'm relatively new to the language.