Navigating JSON data in Typescript/JavaScript

I'm currently looping through JSON data using nested forEach loops in TypeScript. However, I'm curious if there are simpler and more efficient approaches available in typescript or RXJS, especially since I am also iterating over an Observable in some cases. Check out my code snippet and stackblitz demo here

What I want to achieve is to retrieve objects from the JSON data that have a "type" property within the htmltypes array and inlineTags array. Can someone help me with a method to achieve this without using nested forEach loops?

content.data.areas.forEach(sectionBlock => {
  sectionBlock.sections.forEach(obj => {
    obj.htmltypes.forEach(val => {
      console.log(val);
      if (val.inlineTags.length > 0) {
        val.inlineTags.forEach(tag => {
          console.log(tag);
        })
      }
    })
  })
})

Answer №1

If you're looking for a more streamlined approach, you can simplify the nesting using RxJS or array operators such as Array.prototype.flatMap. However, in order to use this method, you'll need to include a polyfill like core-js/es7/array/flat-map. Your code could then appear as follows:

content.data.areas
 .flatMap(sectionBlock => sectionBlock.sections)
 .flatMap(obj => obj.htmltypes)
 .flatMap(val => val.inlineTags)
 .forEach(tag => console.log(tag));

Alternatively, with RxJS, you can achieve similar results:

from(content.data.areas).pipe(
 concatMap(sectionBlock => sectionBlock.sections)
 concatMap(obj => obj.htmltypes)
 concatMap(val => val.inlineTags)
).subscribe(tag => console.log(tag));

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

Creating a JSON object in Ruby: A beginner's guide

Currently working on generating a JSON file using Ruby. In this process, I am trying to define the object "companies" within the JSON structure. Expected output: {"companies":[ {\"label\":\"Wayfair \",\"values\":[54]}, ...

I encountered a problem while integrating antd and moment.js in my React project

I am currently using the antd date-picker in my React project with TypeScript. Encountered an error: Uncaught Type Error: moment is not a function. If anyone has a solution, please assist me. .tsx file:: const dateFormat = 'MM-DD-YYYY'; < ...

Guide on creating a Typescript Conditional type structure for Array elements that rely on each other

In my function, I am working with an array of objects that contain an icon key. If one index in the array has a value assigned to the icon key, then another index should also have a value. If one index leaves the icon key undefined, then another index shou ...

Issue with asmx Web Service causing failure to return JSON data when using FineUploader for file uploads

I acknowledge that there are numerous questions similar to mine regarding this issue, but none of them have provided a solution for me. I understand that web services inherently convert my objects into json as part of the framework. I manually set the requ ...

Processing JSON responses with JQuery AJAX

I am trying to fetch data from a database in the form of a single string row separated by '|' using json, ajax, and WebMethod. JS var request = { RefNo: $('#txtRefNo').val() }; var strRequest = JSON.stringify(request); $('#di ...

Sharing JSON data between components securely without displaying it in the URL through routing

Seeking to pass JSON through routing URL, my code in app.route.ts looks like this: {path: 'calculator', component: CalculatorComponent,data : {some_data : null}}, The code used to route the data is as follows: this.router.navigate(['/home ...

In my Ionic/Angular project, I'm attempting to showcase two columns side by side in a row. However, the layout seems to be stacking them on top of each other with the

I am having some trouble arranging two columns in a row for my Ionic/Angular project. It seems like the content is stacking on top of each other instead of side by side. Here's the CSS I'm using: <ion-grid class="rewards-container&q ...

Self-reference within a JavaScript object involves creating a property that points

Can you reference another part of a JSON object within the same JSON object? In the code snippet below, there is an object that refers to the "home" object within the "MapParameters" object. { "parameters": { "data": { "URL": "http://SC.json ...

The enigmatic dance of Angular and its hidden passcodes

Recently, I've been diving into learning Angular 2 and I'm exploring ways to safeguard the data in my application. I'm curious about how one can prevent data from being accessed on the front end of the app. Could serving the angular app thr ...

Learn how to define an object with string keys and MUI SX prop types as values when typing in programming

I want to create a comprehensive collection of all MUI(v5) sx properties outside of the component. Here is an example: const styles = { // The way to declare this variable? sectionOne: { // What type should be assigned here for SXProps<Theme>? } ...

Guide to transferring an ID received via JSON through Ajax to a PHP POST request

I am struggling with an AJAX function that displays an HTML table. The issue I'm facing is that I have a method in viewmap.php that shows the location based on the ID you click on the table. However, to make this work, I need to send the UID to viewma ...

Is there a conventional method for implementing role-based access control for files in Angular?

I have built 4 projects in Angular that grant access to different roles. The dashboard consists of various content pages, with the initial page being the dashboard when a user logs in. The content displayed on the dashboard is determined by the logged-in ...

Matching the value of an Angular 4 FormGroup with an item in an array

In order to ensure that the input of the country in my form matches one of the countries in my predefined country list, I am looking to implement a custom validation function for my form group. Here is the list of available countries: this.sharedService. ...

mat-slider: experiencing delay in updating while dragging it

Incorporating @angular/material in my Angular 5 application has been quite the journey. The specific version of Angular Material that I have implemented is 5.0.2, along with @angular/animations 5.1.2. My usage of the slider component is rather straightfor ...

Can the Gson Reader only be read once?

Currently, I am experimenting with the Gson parser for handling Json objects and object model. One puzzling aspect that I have come across is why a Reader can only read once? For instance, consider the following code snippet: Reader targetReader = new St ...

Encoding and decoding using Base64-Gzip technology

Recently, I've been monitoring the traffic of an app and noticed that it was sending encrypted requests to its server. The request header looked like this: `eNp1VGtPGzEQ/C/3mUS27x2pUmkLlKZB4VmIIp18thPc3CO1fdAD8d+7Z18gKeFbsjM7O17P+dlb U60fa8W9kffnUSj ...

Utilize ngModelGroup to avoid duplicating the div element

Here is an example of a form layout: <input type="checkbox"> <input type="text"><br> <input type="checkbox"> <input type="text"><br> <input type="checkbox"> <input type="text"> All text fields belong to t ...

Adapting Angular HTTP requests for seamless integration with Azure's app service in the MEAN Stack Environment

After deploying my app to the app service, I encountered a 502 bad gateway error when attempting to log in. While testing locally, I am able to login using http://localhost:3000/api/user/login. As this is my first time deploying to the cloud, I assumed rep ...

The "ngx-places" directive does not have an "exportAs" setting

I recently added the ngx-google-places-autocomplete module to my project. However, upon configuring it, I encountered the following error: core.js:14597 ERROR Error: Uncaught (in promise): Error: Template parse errors: There is no directive with "expo ...

What is the best approach to access the reportProgress of several observables combined within a forkJoin?

I'm currently working on an Angular project where I need to upload multiple files through a form. Each file could be quite large, so I can't just do one POST request with all the files due to server size limits. It would be great if I could impl ...