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

From PHP to Javascript and back to PHP

I'm currently tackling an issue within my project: My database, utilizing PHP, provides an array containing a collection of JavaScript files that require loading. This list is stored in the $array(php) variable. My task is to extract these source fil ...

The 'target' property is not found on the specified 'string' type

I've encountered an issue while creating a search bar in Typescript. Despite my efforts, the input is not being recognized. It seems that whenever I use the term 'target' in my onChange method, it triggers an error stating: Property &ap ...

JavaScript checking the current page's URL is crucial for maintaining accurate and dynamic

I've attempted to verify the URL using this specific function. It functions properly with single text, but fails when a URL is inputted. jQuery(document).ready ( function () { //var regExp = /franky/g; //It works fine ...

Navigation bar theme toggle malfunctioning as anticipated

I'm experiencing an issue with the navbar theme change functionality. Whenever I click on the dark mode button, the theme changes for a brief moment and then reverts back to light mode. <!doctype html> <html lang="en"> <hea ...

Injecting a service into an Angular constant is a straightforward process that involves

Is it possible to define a constant that utilizes the $locale service? Since constants are objects, injecting them as parameters like in controllers is not an option. How can this be achieved? angular.module('app').constant('SOME_CONSTANT&a ...

MDL Tab loading Problem

When visiting my website at this link, which is powered by MDL from Google, there is a troublesome issue that occurs. The #harule tab briefly appears before disappearing. This tab should actually be hidden on the page until a user clicks on the harule tab ...

Creating metadata for a node/npm module build

Looking for a solution to output JSON with build date and updated minor version number using grunt and requirejs for our application. It seems like this would be a common requirement. Any existing tools that can achieve this? ...

Experience the click action that comes equipped with two unique functions: the ability to effortlessly add or remove a class

Currently, I am in the process of creating a list of anchor links that contain nested anchor links, and there are a few functionalities that I am looking to implement. Upon clicking on a link: Add a class of "current" Remove the class of "current" from ...

If there are multiple instances of the component, it may not function properly

I have implemented a Vue component as shown below: <script setup lang="ts"> import { PropType } from "nuxt/dist/app/compat/capi"; interface Star { id: string; value: number; } const stars: Star[] = [ { id: &qu ...

Modify the elements of a matrix by analyzing their surrounding neighbors

I'm working on a script that will transform my matrix A (1x25) into B (1x24) A = [1 1 1 1 0 0 1 1 1 1 0 0 1 1 1 1 0 0 1 0 1 1 1 1 1]; The transformation rule I want to apply is as follows: Two consecutive 1s should be replaced with 1. Two consecut ...

Exploring the contrast between router.pathname and router.route within Next.js

Essentially, my goal is to utilize the NextJS router to access the page url by doing the following: import { useRouter } from "next/router"; const SomeComp = props => { const router = useRouter(); } Yet, when I console.log() the propertie ...

Converting Geometry into BufferGeometry

From my understanding, Geometry contains a javascript object structure of the vertices and faces, while BufferGeometry stores raw WebGL data using Float32Arrays, etc. Is there a method to convert regular Geometry into BufferGeometry, which is more memory ...

Incorporate an HTTP Header into a Wicket Ajax Request

I am trying to include a custom HTTP header in all Ajax (XHR) requests made by Wicket. I attempted the following: $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('X-My-Header', 'value'); } }); and $(doc ...

Adjust the FlipClock time based on the attribute value

When setting up multiple FlipClock objects on a page, I need to retrieve an attribute from the HTML element. The specific HTML tag for the clock is: <span class="expire-clock" data-expire="2015-09-22"> Is there a way to access '2015-09-22&apos ...

Transforming a base64 encoded string into a byte array

I have implemented a form where users can upload images to the page using an <input id = "fileLoader" type = "file" />. With JavaScript, I convert these uploaded images to base64 and send them to the server. On the server side, I need to decode this ...

Ways to identify when the scroll bar reaches the end of the modal dialog box

I have been working on a modal that should display an alert when the scrollbar reaches the bottom. Despite my efforts to research a solution, I am struggling to detect this specific event within the modal. The desired outcome is for an alert to pop up once ...

Utilizing the power of jQuery within three.js

Thank you once again for your previous assistance, but I find myself in need of your expertise once more. I have successfully added markers to my map as desired. However, these markers now require functionality to be clickable. Specifically, when clicked, ...

Library of Angular components - utilizing images in templates

I am currently using an npm package that contains several angular components. These components reference images in their templates. I have noticed that if I manually copy the images to my application's images directory, the references are resolved. Ho ...

Dependency on the selection of items in the Bootstrap dropdown menu

I am currently struggling with a few tasks regarding Bootstrap Dropdown Selection and despite looking for information, I couldn't find anything helpful. Check out my dropdown menu Here are the functions I would like to implement: 1) I want the subm ...

Validating forms in ReactJS

I have developed a basic form validation feature for React. The inspiration for this project came from the following source: When I try to submit the form, input errors arise within the isValid function. I am seeking assistance in resolving this issue. A ...