Unlocking selective information from nested arrays with .map or flatmap in Angular 2/Typescript

I have the following JSON data:

{   "damages": {        "regions": [{
                "name": "External Damages",
                "totalEstimatedCost": "$ 0.00",
                "damageDetails": [{
                    "areaDes": "FRONT Hood",
                    "type": "Prev Repair",
                    "desc": "Acceptable",
                    "estimate": "$ 0.00",
                    "isClickable": true,
                    "regularUrl": "https://adesa.test2.kar-media.com/display.php?img=283509519_d_ee9339f0-d9d9-48cb-ab15-66831f95dcd7-Original.jpg",
                    "midSizedPath": "https://adesa.test2.kar-media.com/display.php?img=283509519_d_ee9339f0-d9d9-48cb-ab15-66831f95dcd7-Original_lb.jpg",
                    "thumbNailPath": "https://adesa.test2.kar-media.com/display.php?img=283509519_d_ee9339f0-d9d9-48cb-ab15-66831f95dcd7-Original_th.jpg"
                }]          },          {
                "name": "Other Damages",
                "totalEstimatedCost": "$ 0.00",
                "damageDetails": [{
                        "areaDes": "FRONT Front Bumper Cover",
                        "type": "Prev Repair",
                        "desc": "Acceptable",
                        "estimate": "$ 0.00",
                        "isClickable": true,
                        "regularUrl": "https://adesa.test2.kar-media.com/display.php?img=283509519_d_ee9339f0-d9d9-48cb-ab15-66831f95dcd7-Original.jpg",
                        "midSizedPath": "https://adesa.test2.kar-media.com/display.php?img=283509519_d_ee9339f0-d9d9-48cb-ab15-66831f95dcd7-Original_lb.jpg",
                        "thumbNailPath": "https://adesa.test2.kar-media.com/display.php?img=283509519_d_ee9339f0-d9d9-48cb-ab15-66831f95dcd7-Original_th.jpg"
       ... (content shortened for brevity) ...
                    }
                ]           }       ],      "totalDamages": 10,         "totalCost": "$ 0.00"   } }

In the above JSON data, I am looking to extract all regularUrls into a single array. How can this be achieved using mapping in Angular 2/TypeScript/RxJS?

Currently, I am using two for loops or three .maps functions to compile the regularUrls into one array.

Is there a way to solve this using RxJS or TypeScript in Angular 2?

Any guidance on potential solutions would be greatly appreciated. Thank you.

Answer №1

Check out this code snippet:

 var data = { "damages": { "regions": [{
          "name": "External Damages",
          "totalEstimatedCost": "$ 0.00",
          "damageDetails": [{
            "areaDes": "FRONT Hood",
            "type": "Prev Repair",
            "desc": "Acceptable",
            "estimate": "$ 0.00",
            "isClickable": true,
            "regularUrl": "https://adesa.test2.kar-media.com/display.php?img=283509519_d_ee9339f0-d9d9-48cb-ab15-66831f95dcd7-Original.jpg",
            "midSizedPath": "https://adesa.test2.kar-media.com/display.php?img=283509519_d_ee9339f0-d9d9-48cb-ab15-66831f95dcd7-Original_lb.jpg",
            "thumbNailPath": "https://adesa.test2.kar-media.com/display.php?img=283509519_d_ee9339f0-d9d9-48cb-ab15-66831f95dcd7-Original_th.jpg"
          }] }, 
          {
          "name": "Other Damages",
          "totalEstimatedCost": "$ 0.00",
          "damageDetails": [{
            "areaDes": "FRONT Front Bumper Cover",
            "type": "Prev Repair",
            "desc": "Acceptable",
            "estimate": "$ 0.00",
            "isClickable": true,
            "regularUrl": "https://adesa.test2.kar-media.com/display.php?img=283509519_d_ee9339f0-d9d9-48cb-ab15-66831f95dcd7-Original.jpg",
            "midSizedPath": "https://adesa.test2.kar-media.com/display.php?img=283509519_d_ee9339f0-d9d9-48cb-ab15-66831f95dcd7-Original_lb.jpg",
            "thumbNailPath": "https://adesa.test2.kar-media.com/display.php?img=283509519_d_ee9339f0-d9d9-48cb-ab15-66831f95dcd7-Original_th.jpg"
          },
          {
            "areaDes": "INT OPT Gas",
            "type": "Empty",
            "desc": "Unacceptable",
            "estimate": "$ 0.00",
            "isClickable": true,
            "regularUrl": "https://adesa.test2.kar-media.com/display.php?img=283509519_d_ee9339f0-d9d9-48cb-ab15-66831f95dcd7-Original.jpg",
            "midSizedPath": "https://adesa.test2.kar-media.com/display.php?img=283509519_d_ee9339f0-d9d9-48cb-ab15-66831f95dcd7-Original_lb.jpg",
            "thumbNailPath": "https://adesa.test2.kar-media.com/display.php?img=283509519_d_ee9339f0-d9d9-48cb-ab15-66831f95dcd7-Original_th.jpg"
          },
          // more damage details...
        ] } ], "totalDamages": 10, "totalCost": "$ 0.00" } }
        
        // Filter and map through the data
        data.damages.regions.filter(item=>item.hasOwnProperty('damageDetails'))
                .map((item, i) => item.damageDetails.map((it,j)=> console.log(it.regularUrl)))
      

Answer №2

you have the option to implement a similar approach

let regularUrls = []; 

damages.regions.filter(region => region.hasOwnProperty('damageDetails') && region.damageDetails.length).map(region => {
    regularUrls = regularUrls.concat(region.damageDetails.map(damage => damage.regularUrl));
});

the regularUrls array will store all the regular Urls.

Take advantage of this fiddle for testing purposes http://jsfiddle.net/IbraheemAlSaady/xtr81m74/

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

Verify that each interface in an array includes all of its respective fields - Angular 8

I've recently created a collection of typed interfaces, each with optional fields. I'm wondering if there is an efficient method to verify that all interfaces in the array have their fields filled. Here's the interface I'm working wit ...

What is the best way to create a TypeScript type for React props that only allows prop B to be used if prop A is included in the component?

My component Text has 2 props: isHideable: boolean and hidden: boolean. How can I only allow Hidden as a prop when isHideable is set to true? Currently, both isHideable and hidden are being accepted which is not the desired behavior: type Props = { chi ...

Error Encountered: Kendo Angular 4 Peer Dependency Issue and Module "rxjs/operators/combineLatest" Not Found

I'm currently facing issues while attempting to integrate Kendo UI into an Angular 4 application, encountering various errors along the way. To begin, I initiated the installation by running this command: npm install --save @progress/kendo-angular-d ...

Implement dynamic typing in the sort function to restrict it to only accept number properties

I need help creating a pipe that can sort an array of objects based on a specified property. While I have managed to make it work, I am encountering a type error in my code. Here is the snippet: export const sortByProperty = <T>(a: T, b: T, property: ...

The integration of Angular and Node API within the IISNode directory structure is experiencing functionality issues

Read more about the question I have successfully set up my Node API and Angular component with IISnode. However, when accessing the application from the IIS server, I noticed that they are showing in different directories (see image below). Additionally, I ...

Guide to specifying a type as optional based on specific criteria

In coding, there exists a certain type that is defined as follows: type PropsType = { dellSelectedOption: (id: string, idOptions: string[]) => void; ownFilterData: Array<ActiveFilterAndPredFilterDataType>; watchOverflow: boolean; childre ...

A guide on implementing a Type Guard check for an Indexed Property

I am working with a nestedObj type that utilizes an indexed signature like this: type nestedObj = {[key: string]: nestedObj} | {[key: string]: number} How can I go about creating a type guard for this nestedObj type? const isNestedObj = (obj: any): obj ...

Receiving a CORS issue while integrating Django as the backend for an Ionic application

I have integrated Django Rest Framework as a backend for my Ionic application. The API setup using JWT is successfully tested with Postman. However, when attempting to make an API call from the Ionic app, I encounter the following errors: Error 1 Cross-Or ...

Having trouble retrieving spot price using Uniswap SDK due to a transaction error LOK

const quotedAmountOut = await quoterContract.callStatic.quoteExactInputSingle( immutables.token0, immutables.token1, immutables.fee, amountIn, 0 ) I set up a pool on Uniswap V3 for two ERC20 dummy tokens by using the createPool() met ...

Is there a method to improve type inference in vscode?

Recently, I created a component with a click handler that looks like this: onClick={(e) => { e.stopPropagation(); }} It seems clear to me, but then the Typescript compiler complains that it's not a valid signature for onClick, which actually a ...

Tips for effectively constructing and optimizing an Angular 5 Project

As a newcomer to an Angular 5 project, I recently executed the command ng build --prod which resulted in the generation of a dist/ folder. To my surprise, the building process took significantly longer than expected. Upon inspecting the contents of the di ...

Encountering an issue with a specific property not being defined in a spec

I am currently developing an Angular8 project and have set up jest and jasmine for testing purposes. .ts // all necessary imports are included @Component({ selector: 'app-xyz', templateUrl: './xyz.component.html', styleUrls: [& ...

A guide on utilizing ngx-translate to convert validation messages in Ionic4

In my ionic4 application, I am configuring it to support two languages - ar and en using ngx-translate library. I have two JSON files, en.json and ar.json, with the following structure: { "LOGIN": { "login": "Login", "emailOrPhone":"EMAIL OR PHO ...

Can Angular 4 experience race conditions?

Here is a snippet of my Angular 4 Service code: @Injectable() export class MyService { private myArray: string[] = []; constructor() { } private calculate(result): void { myArray.length = 0; // Perform calculations and add results to myAr ...

Configuration file for proxying both HTTP requests and WebSockets to the same endpoint

In my development environment, I have successfully set up a proxy for http requests to a django server on my backend/laptop using a proxy.conf.json configuration file: { "/graphql": { "target": "https://localhost:443/gr ...

Can you provide instructions on how to display data in two lines within a mat-select field?

Is it possible to show selected options in mat-select with long strings in two lines within the same dropdown? Currently, the string appears incomplete. You can see an example of this issue here: incomplete string example <mat-form-field class="f ...

Learn the art of bypassing TypeScript errors using @ts-ignore!

I recently encountered an issue when trying to import a pure JavaScript library into a TypeScript project, resulting in the error message: Could not find a declaration file for module xxx. After some research, I learned that this error can be suppressed u ...

"Obtaining Google locations within a modal box - a step-by-step

Having trouble with my Google Places search integration in Angular 2. <input type="text" type="text" class="form-control" placeholder="Address" [ngClass]="{active:signupSubmitted && !signUpForm.controls['formatted_address'].valid}" [ ...

What is the best way to create buttons corresponding to the total number of "postId" properties in an array retrieved from an API call in Angular 10 using the "ngFor" directive?

export class AlphaComponent implements OnInit { apiData=[]; //array that stores API data constructor(private helpService:HelpService){ }; ngOnInit(){ this.fetchData() }; fetchData(){ this.helpService.getPostId().subscribe(( ...

Enable table cell editing in Angular 2 on click event

I am working on a task where I have an ngFor loop for rows, and I want to make it so that when I click on a cell, it becomes editable. <tr *ngFor="let invoice of invoiceItem.rows"> <td contenteditable='true' (input)="onRowClick($eve ...