loop through nested arrays

My goal is to use ng repeat in Angular to iterate through a child array of a multidimensional array. The json object I am working with is as follows:

 $scope.items =   [{    "id":1,
        "BasisA":"1",
        "Basis":true,
        "personSex":"m",
        "isCollapsed":false,
        "name":"Mark Polos",
        "age":"1955",
        "results":[{"1000":{"company_name":"***","model":"***","modelname":"***","pr":222,"rating":4.5,"priority":9,"matching":1},
                    "1001":{"company_name":"***","model":"***","modelname":"***","pr":228.7,"rating":5.7,"priority":7,"matching":2},
                    "1002":{"company_name":"***","model":"***","modelname":"***","pr":241.7,"rating":1.9,"priority":4,"matching":3}
                }]
    }]

I attempted the following approach:

... data-ng-repeat="item in items">

And then for each item in the table:

<tr data-ng-repeat="i in item | orderBy:'insItem.pr'">

Answer №1

It appears that the results property is not structured as a typical "array." If this is simply a mistake in your example, then please disregard this message. However, if it is intentional... read on.

The structure seems to be an array with a single item, where that item contains properties which are objects themselves. To access the property "pr" for the result named "1000," you would use code like item.results[0]["1000"].pr instead of the code expected by ng-repeat (item.results[0].pr).

Is there a way to convert your items so that results becomes a proper array?

Alternatively, could you create a function within your controller to return the desired array?

View Code:

<... data-ng-repeat="result in resultsFromItem(item)" >

Controller Code:

$scope.resultsFromItem = function (item) {

   if(item==undefined || item.results==undefined || item.results.length==0) {
      return [];
   }

   var myResults = [];
   for (var key in item.results[0]) {
      if(item.results[0].hasOwnProperty(key)) {
         myResults.push(item.results[0][key]);
      }
   }

   return myResults;

}

You may even consider attaching the transformed results object to each item object (to only perform the transformation once) if needed.

Answer №2

To retrieve the desired information, make sure to interact with the results section:

... data-ng-repeat="element in elements">

<tr data-ng-repeat="subElement in element.results">

This is necessary because the nested array containing the data is located within the results attribute of the primary object.

Answer №3

I implemented a solution using three nested ng-repeat directives to achieve the desired outcome :-) In the third ng-repeat, I utilized the functionality of

ng-repeat="(key, value) in result"
to display all keys and values of the result object. This was made possible with the assistance of an answer found on how to iterate over keys and values in ng-repeat. Although the orderBy: section is not functioning as intended at the moment (any insights on how to implement this would be greatly appreciated).

    <ul>
      <li ng-repeat="item in items">
         id: {{item.id}}, name: {{item.name}}, age: {{item.age}}, results: 
         <table>
           <tr ng-repeat="result in item.results">
             <td>
               <table style="border: 1px solid black;">
                  <tr ng-repeat="(key, value) in result | orderBy: value.pr">
                    <td> {{key}} </td> <td> {{ value }} </td>
                  </tr>
              </table>
            </td>
          </table>
      </li>
    </ul>

Plunker

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

A guide to removing functions from the render method

Greetings! Currently, I am in the process of creating a simple webpage that utilizes a map function to display all details to the user. Some fellow developers have advised me to remove my functions from the render method, as it continuously renders unneces ...

Combine the entities within the object

I need to combine two objects that contain other objects within them, similar to the following structure: let selections = { 123: { abc: {name: 'abc'}, def: {name: 'def'} }, 456: { ghi: {name: ' ...

Optimizing Midnight UTC+0 Setting in JavaScript Date Functions

I am using an MUI Datepicker that allows me to choose a day without specifying the time. For example, if I select 01.09.1970, in the console log it displays as Tue Sep 01 1970 00:00:00 GMT+0100 (Central European Standard Time). This indicates that even tho ...

When working with data in Angular, make sure to use any[] instead of any in app.component.html and app.component.ts to avoid causing overload errors

I'm new to working with Angular, specifically using Angular 15. I have a Rest API response that I need to parse and display in the UI using Angular. To achieve this, I employed the use of HttpClient for making GET requests and parsing the responses. ...

Button to close Jquery Dialog

I've set up a custom alert UI using jQuery UI, but I'm having trouble getting the close button to work properly. Here's my code snippet where I'm trying to override the default alert() function with jQuery UI dialog as described in this ...

Organizing a NodeJS module - properties and functions

I've been struggling to structure my NodeJS application with modules, and after hours of searching, I haven't found a definitive answer. Let's say I want to create a "user" module for creating new users in my code: var newUser = new User(); ...

Ways to decrease the size of this item while maintaining its child components?

Here is an object that I am working with: { "name": "A", "children": [ { "name": "B", "open": false, "registry": true, "children": [ { ...

What impact does nesting components have on performance and rendering capabilities?

Although this question may appear simple on the surface, it delves into a deeper understanding of the fundamentals of react. This scenario arose during a project discussion with some coworkers: Let's consider a straightforward situation (as illustrat ...

Using PHP to send post requests with Ajax for DataTables functionality

I'm currently working on populating a datatable using datatables.net. There's a specific field that triggers an AJAX post request after it's changed. Here is the JavaScript code: jQuery(document).ready(function() { if(window.location.h ...

Using an external JavaScript script may encounter difficulties when loading pages with jQuery

Trying to utilize jQuery for loading html posts into the main html page and enabling external scripts to function on them. Utilizing a script (load.js) to load posts into the index.html page: $(document).ready(function () { $('#header').loa ...

Change ES6 JavaScript to ES5 standard

Is there a way to transform this code snippet from other questions into ES5 format? I am attempting to extract data from a JSON array. var match = function(query, input) { return input.filter(function(entry) { return Object.entries(query).every(fun ...

What are Fabric.js tools for "Drop Zones"?

Has anyone successfully created a "drop zone" similar to interact.js using fabric.js? I haven't had the chance to experiment with it myself. I have some ideas on how I could potentially implement it, but before diving in, I wanted to see if anyone el ...

Automatically collapse the Shadcn-UI Accordion when the mouse exits

For my self-education project, I am working on building a sidebar with an accordion using Shadcn-ui, NextJS (13.4), React, and Node. Being new to these technologies, I have encountered a problem that I can't seem to solve. The sidebar expands on mous ...

The debate between client-side and server-side video encoding

My knowledge on this topic is quite limited and my Google search didn't provide any clear answers. While reading through this article, the author mentions: In most video workflows, there is usually a transcoding server or serverless cloud function ...

Automatically tapping the Quora "expand" button through code

I am attempting to automate the clicking of the "more" button located at the bottom of a page like using watir. Below is the code I currently have: require 'watir-webdriver' b = Watir::Browser.new b.goto 'quora.com/'+ ARGV[2] + ' ...

Getting js.map Files to Function Properly with UMD Modules

I am experiencing an issue with debugging TypeScript files in Chrome and Firefox. Specifically, when trying to debug the MapModuleTest.ts file, the debugger seems to be out of sync with the actual JavaScript code by two lines. This discrepancy makes settin ...

What are some effective ways to analyze jQuery and JavaScript using web development tools?

I'm struggling to use web development tools to inspect the JavaScript on websites. It's challenging to identify which parts of a site are utilizing JS, unlike CSS or HTML where it's more visibly defined. Even when I attempt to delete some J ...

Is there a way to efficiently retrieve multiple values from an array and update data in a specific column using matching IDs?

In my Event Scheduler spreadsheet, I am looking for a way to efficiently manage adding or removing employees from the query table in column A. Currently, I have a dropdown list in each row to select names and a script that can only replace one name at a ...

Struggling to concentrate using jQuery?

When the search icon is clicked, I want the focus to be on the input so the user can start typing right away without having to manually click on it. Although I tried using focus(), it doesn't seem to work for this particular input. $('.header__ic ...

Ways to verify AJAX Response String when data format is specified as JSON

When using AJAX to retrieve JSON data from a webpage, it's essential to set the responseType to json. If the data processing is successful, a valid JSON string is returned, which works perfectly. However, if there's an error on the webpage, inst ...