How to access nested JSON elements in Javascript without relying on the eval function

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.

Answer №1

To ensure the status remains constant once loaded, save the value of data.orders.status to a variable and reference that variable throughout your code.

public static STATUS : string = data.orders.status;

(or use whichever syntax is appropriate for typescript).

If the status has the potential to change after the page has loaded, create a function and invoke that function in your code:

function getStatus() { return data.orders.status; }

In either scenario, the object structure required to access the status field is only specified once within the code.

Answer №2

Here's a different approach: why not store the keys in a list and then compute the value by retrieving the values of those keys sequentially. Since I'm not familiar with TypeScript, I'll provide my solution using JavaScript for reference.

public static STATUS : string = ["orders", "status"];
var status_value = angular.copy(data);
STATUS.forEach(function(key){
     status_value = status_value[key];
});

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

ASP.NET AJAX UpdatePanel - preventing postback in InitializeRequest will not reset back to enabled state

In my ASP.NET AJAX UpdatePanel, there is a submit button with custom javascript validation that sets a global flag called _cancelGeneralSettingsUpdate based on the validation results. Everything works fine except when an invalid value is entered, correcte ...

The initial res.body object in NodeJS is enclosed in quotation marks

I've hit a roadblock while working on my social media website project using the MERN stack. Despite scouring the internet, I haven't been able to find a solution to the issue at hand. While following an online course, I encountered a problem tha ...

The HTTPOnly cookie is not accessible within the getServerSideProps function in Next.js

Why isn't the jid cookie available in getServerSideProps using Next JS? Here's the scenario: https://i.stack.imgur.com/FLRGk.png The jid cookie is generated by an Expressjs API at https://api-dev.example.com. I'm attempting to retrieve thi ...

Utilize Grunt to retrieve a JSON object from a file

I'm interested in utilizing the grunt-hash plugin to rename my JavaScript files. This plugin generates a new file that contains a map of renamed files: hash: { options: { mapping: 'examples/assets.json', //mapping file so your s ...

What are some best practices for implementing pagination using Angular Material?

While following a tutorial by Muhi Masri on how to implement an Editable Dynamic Table using Angular Material Paginator (the tutorial can be found here, highly recommended), I encountered an issue where the paginator was not working as expected. Despite fo ...

The video rendered with fluent-ffmpeg appears to have an elongated image

I am working on combining an mp3 audio file with a jpg image file to create a new mp4 video. Although I have a functional fluent-ffmpeg command that accomplishes this task, there is an issue where the image gets stretched in the final output video, especia ...

Using async/await with mysql2 in Node.js can lead to undefined rows and fields

I am facing an issue where the query below is returning undefined in rows and field even though the user table has data. How can I properly use the promise version in TypeScript? Any help would be greatly appreciated. Thank you... code import mysql from ...

How can I extract the text from a textarea in react-bootstrap and pass it to a function when a button is clicked?

Below is the React-Bootstrap code that I am working with: <Form> <Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1"> <Form.Label>Example textarea</Form.Label> <Form.Control as=&quo ...

Is there a way to rotate label text on a radar chart using chart js?

I am working with a Chart js radar diagram that contains 24 labels. My goal is to rotate each label text by 15 degrees clockwise from the previous one: starting with 'Label 1' at the top in a vertical position, then rotating 'Label 2' ...

What is the purpose of exporting both a class and a namespace under the same name?

While exploring some code, I came across a situation where a class and a namespace with identical names were exported from a module. It seems like the person who wrote this code knew what they were doing, but it raised some questions for me. Could you shed ...

Transformation of characters with diacritics in DataWeave output

My JSON response contains special characters including German umlauts (ä,ö,ü). Despite setting the encoding to UTF-8, the output from dataweave shows as ü and ä and ö, and it is identified as com.mulesoft.weave.reader.ByteArraySeekableStream d ...

Do async functions in javascript function synchronously in reality?

I am currently exploring the inner workings of asynchronous code in Javascript. From my understanding, there exists a single thread in JS responsible for executing tasks in a queue. It can progress to the next task only after finishing the current one, whe ...

Transforming data from an HTML form into a PDF document - Tips for generating multiple outputs

As a newcomer to coding, I am facing a challenge in passing input data from a form to a PHP response page and then displaying it in the browser. I have created a functionality where the user can click on a button to save the HTML element to PDF. However, I ...

Utilizing the `useNavigate` function from react-router v6 within a class component to navigate and manage

I have a situation where I need to redirect a class component to another page. To achieve this, I came up with a function that decorates the export of the class component in order to navigate within the component's state. import { useNavigate } from & ...

Ways to access text content in an HtmlTableCellElement

I am currently working on a jQuery tic-tac-toe project and facing an issue with iterating through the board to save the values of each cell in an array. I have tried using .text() and .value(), but both returned undefined index.html: <html> < ...

Unable to declare an "if statement" within a Jasmine JS test scenario

I'm having trouble creating an "if statement" inside my test case using Jasmine JS. The error seems to be related to a wrong locator, but I suspect it might actually be due to a syntax issue. ** Pay attention to the code block of "screen 4" ** desc ...

Personalized dropdown appearance

During my work on a select box, I discovered that custom styling is not possible. I attempted to use some plugins but did not find one that met my needs. I am seeking a dropdown menu with options in both black and gray, similar to this template but using ...

How to Generate Custom Expiry Tokens with Firebase Authentication

Currently utilizing Firebase 3.4.1 for my web application. The default token expiry length is sufficient to keep users logged in, but I am interested in managing the expiry manually. Ideally, I would like the token to expire at the end of each session by ...

What steps do I need to take to set up Vue-CLI 3 to generate a webpage with no JavaScript?

My dilemma is this: I have a simple static page that does not require JavaScript. Using vue-cli 3, I am attempting to pass the HTML file through webpack for minification purposes. Unfortunately, it seems that accomplishing this task is not as straightforwa ...

Looking for the location of the traceResolution output?

When I enable traceResolution in my tsconfig.json file, where can I expect to see the resulting output? { "compilerOptions": { "traceResolution": true, ... The --traceResolution flag enables reporting of module resolution log messages. You ...