What is the best way to access a nested array from a JSON response in Angular 10?

  "CongnitiveSearchResult":{
      "value":[
         {
            "DisplayTags":[
               "Cross-Function",
               "Retail",
               "Oil & Gas",
               "Manufacturing"
            ]
         }

I need to calculate the length of displaytags in each response, such as response[o] having a length of 3, and I have to repeat this process for every response. This information needs to be displayed and looped through in HTML within each div. The issue arises when the length is not consistent for each response - for example, the length of the display tags in the '0th' response shows as 1 but the actual length is 3, causing confusion. It's important to note that sometimes displaytags may be empty or null.

Answer №1

If you wish to loop through them in a template, use the DisplayTags array instead of just their length.

To access all elements in the DisplayTags array

  displayTags: string[][];

  constructor() {
    this.displayTags = CongnitiveSearchResult.value.map((o) =>
      o.DisplayTags ? o.DisplayTags : []
    );
  }

In the template for iteration:

<div *ngFor="let arr of displayTags">
  <div *ngFor="let item of arr">
    {{ item }}
  </div>
  <hr />
</div>

Alternatively, to display based on value

<div *ngFor="let val of CongnitiveSearchResult.value">
  <b>Name</b> : {{ val.Name }}<br />
  <b>Display Tags:</b>
  <ol>
    <li *ngFor="let item of val.DisplayTags ? val.DisplayTags : []">
      {{ item }}
    </li>
  </ol>
  <hr />
</div>

Live Demo

Answer №2

Follow these steps to achieve it:

let response_displaytags_lengths = CongnitiveSearchResult.value.map(item => item.DisplayTags? item.DisplayTags.length: 0);

Check out this practical demonstration:

const CongnitiveSearchResult = {
  "value":[
     {
        "@search.score":6.755926,
        "Id":"932b3a70-630e-4fb8-3a8d-08d91c6c03ac",
        "Name":"ZBS Closed Loop",
        "ShortDescription":"All six phases of the ZBS closed loop framework which help drive sustainable outcomes for clients",
        "Description":"All six phases of the ZBS closed loop framework which help drive sustainable outcomes for clients",
        "Date":"2021-05-21T15:20:49.317Z",
        "Type":"Project Model",
        "DisplayOrder":31,
        "ArchetypeVersionUId":"e959266c-0711-443b-6b1b-08d91c6c03d4",
        ...
          
let response_displaytags_lengths = CongnitiveSearchResult.value.map(item => item.DisplayTags? item.DisplayTags.length: 0);
console.log(response_displaytags_lengths)

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

Implement lazy loading of content on scroll in Grails framework

Currently, I am uploading images and displaying them in a gsp view. My goal now is to implement a functionality where the images load as I scroll down on the page. A friend suggested using jQuery to make an ajax call for this. Can someone please provide g ...

Is Angular equipped with named routes or states similar to UIRouter?

When working with AngularJS and ui-router, we define a state like this: .state('myState', { url: 'some-user-friendly-url' ... }) This allows us to easily specify the URL and name of the state. It simplifies navigation by letting ...

Consistent integration into React component

I'm currently working on an application using the React library, but my current challenge lies within JavaScript ES6 itself. Within a component (page) that I've created, I have implemented a custom Floating Action Button (FAB): class Page exten ...

Issue encountered when populating FormArray with a FormGroup inside a loop in Angular version 17

Encountering an error while trying to populate a FormArray in Angular (version 17): Issue arises at line 44 with the error message: Argument of type 'FormGroup<{ name: FormControl<string | null>; amount: FormControl<number | null>; }&g ...

Transfer selected option with various values using JavaScript from one list to another

Currently, I am experimenting with creating a Dual List Box for forms that involve multiple selections. This setup includes two lists: one containing options to choose from and the other displaying the selected options. My approach involves using vue2 alon ...

Using Three.js to create a blurred SVG texture from a canvas

I am attempting to apply an SVG as a texture over a model with UV mapping, but it appears very blurry. I'm using the texture from a 2D canvas, which looks fine on its own, but once applied to the model, it doesn't look good at all. Any suggestion ...

Passing events between sibling components in Angular 2Incorporating event emission in

Having some trouble emitting an event from one component to another sibling component. I've attempted using @Output, but it seems to only emit the event to the parent component. Any suggestions? ...

Conceal a table row (tr) from a data table following deletion using ajax in the CodeIgniter

I am attempting to remove a record in codeigniter using an ajax call. The delete function is functioning correctly, but I am having trouble hiding the row after deletion. I am utilizing bootstrap data table in my view. <script> function remove_car ...

What is the method for providing a date format choice in JSON?

I am encountering an issue in my PHP script where I use JSON to pass parameters. When I pass the date as "09-09-2015", it functions correctly. However, when I try to pass the date as $date, it does not work. How can I resolve this problem? $item1 = "test ...

What could be the reason for the HTML canvas not displaying anything after a new element is added?

How come the HTML canvas stops showing anything after adding a new element? Here is my HTML canvas, which works perfectly fine until I add a new element to the DOM: <canvas class="id-canvas", width="1025", height="600"> ...

Angular 2 .net core project experiencing issues with missing files in the publish folder

Exploring the Angular 2 template within a .NET Core framework, as detailed in this resource . However, upon publishing the solution, I noticed that all the files within the "app" subfolder of ClientApp are missing. This leads to a situation where my esse ...

Assign a specific material to a specific portion of a mesh in Three.js

In the world of three.js, imagine having a 3DObject that looks something like this: const geometry = new THREE.BoxGeometry(1, 1, 1); const material = new THREE.MeshStandardMaterial({ color: 0xff0000 }); const mesh = new THREE.Mesh(geometry, material); ...

What is the reason behind having to coerce the enum value before the object type can be properly recognized?

My object is discriminated based on the type property, which can be any value from a specified enum. I encounter an issue in TypeScript when passing a valid object to a function; it complains about mismatched types. However, coercing the enum value resolve ...

The properties are not compatible with the expected types for a Next.js page

On my next.js website, I have created a page.tsx that should take in two props. Even though Visual Studio Code is not showing any errors, I encountered the following error message during the website build: Failed to compile. app/(Dashboard)/(practice)/pra ...

Upon implementing a catch-all express routing solution, the Fetch API calls are no longer successful. The error message received is "Unexpected token < in JSON at

While working on a React project, I encountered an issue outlined in this link: React-router urls don't work when refreshing or manually typing. To resolve this problem, I decided to implement the "Catch-All" solution recommended in that discussion. ...

Execute the laravel {{action(Controller@method}} by sending a parameter from a vue.js array

Within my view created using Blade templates, I have a link with an href attribute that directly calls a Controller method. Here is an example: <a id="@{{user.id}}" href="{{action('Controller@method')}}">>update</a> Everything wo ...

Apply geometric principles to the physical world

In an attempt to accurately scale my geometry to match real-world dimensions in my 3D scene, I am facing some challenges. I extract the coordinates of the top left and top right corners of my map, convert them into points using Google Maps projection, an ...

What is the procedure for accessing the export function of photoeditorsdk in order to retrieve the image URL?

I am facing difficulty retrieving the updated image URL from the PhotoEditor SDK. This issue arises while trying to integrate the PhotoEditor SDK with Angular. let templateStr: string = ` <ngui-react [reactComponent]="reactComponent" [react ...

Redis method LRANGE is returning a list in a way that doesn't meet my requirements

I have a significant amount of data stored in redis which I am caching. When I need to retrieve this data, I use the lrange function to fetch it. The issue is that when the data is returned, it is in a format like this: https://i.sstatic.net/r1oa8.png Ho ...

Incorporate dc.js into your Cumulocity web application

Our team is facing a challenge while trying to integrate dc.js into our Cumulocity web application. While the standalone version works perfectly, we encounter issues when attempting to use it within Cumulocity. Below is the code for our standalone applica ...