Techniques for iterating through an array within another array using AngularJS

I am working with a limited number of records and attempting to utilize a foreach loop in the controller.

var values = [[{"code":"sd","description":"d"}],[{"code":"gh","description":"d"}]]

angular.forEach(values, function(value, key){
console.log(key + ': ' + value.code);
});

This particular data structure returns an object nested within another array. I would appreciate any suggestions on how to effectively use a foreach loop to extract the 'code' value from this dataset.

Answer №1

Performing a nested foreach loop

const itemList = [];

angular.forEach(dataList, function(data, key){
  angular.forEach(data.items, function(item, key){
      itemList.push(item.code);
   });
});

Answer №2

let information = [[{"identifier":"xyz","details":"abc"}],[{"identifier":"123","details":"def"}]]

for (let x = 0; x < information.length ; x++){
   for (let y = 0; y < information[x].length ; y++){
      console.log(information[x][y])
   }
}
  • The conventional for loop outperforms angular.forEach by approximately 90% in speed.

  • Additionally, the angular.forEach loop does not support breaking based on a condition match.

Answer №3

Enhancing the capabilities of arrays by extending the Array prototype allows for efficient manipulation and operations in a functional programming approach. The snippet below showcases how this can be achieved:

arr.flatten().select('code').forEach(function (code) { console.log('code: ' + code) })

To implement these functions in your own code, you will need to include them as shown below:

Array.prototype.select = function (prop) {
   var arr = this;
   var ret = [];
   for (var i = 0; i < arr.length; i++) {
       ret.push(arr[i][prop]);
   }
   return ret;
}
Array.prototype.flatten = function () {
   var arr = this.valueOf();
   var ret = [];
   arr.forEach(function (item) {
       if (Array.isArray(item)) {
           item.forEach(function (itm) {
               ret.push(itm);
           });
       }
       else {
           ret.push(item);
       }
   });
   return ret;
}

If you find this useful, you may want to explore additional array manipulation functions available at https://github.com/mykeels/ArraysJS. There is a variety of other helpful functions waiting to be discovered.

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

Retrieving data from an HTML Table using Javascript

I am in the process of designing a dynamic web form that populates from a stored procedure. The form consists of a table with a dropdown list, a text box, and a label. While I can successfully retrieve data from the dropdown and text box, I am facing diffi ...

Unexpected display of Unicode text retrieved through ajax requests

In my setup, I have both an admin module and a front end module available. Specifically, there is a category section that plays a key role in the functionality. To create categories, I utilize AJAX to send data from a text box to PHP. It's important ...

I am looking to retrieve information from mongodb and then transform it into a JSON object using node.js. Can you guide

I am on a mission to retrieve data from a MongoDB database and transform it into a JSON object in Node.js. The goal is to be able to easily manipulate this data as if it were a simple JSON object. Here's the current code snippet I'm working with: ...

Switch the design and save it in the browser's cache

Exploring the possibility of having two themes, "dark" and "light," that toggle when a checkbox is clicked. To implement the theme change, I used the following JavaScript code: document.documentElement.setAttribute('data-theme', 'dark&apos ...

Place an image at the center with a height set to 100% within a div that has a fixed height and

Apologies for asking about this topic again, but I have been unable to find a solution where the image fills 100% of the height. If you'd like to see the issue in action, here's a link to the jsfiddle: http://jsfiddle.net/BBQvd/3/ I'm just ...

When accessing the route "/[locale]", make sure to await the `params` object before utilizing its properties like `params.locale`

Currently, I am developing a Next.js 15 application utilizing the new App Router (app directory) with dynamic route localization. Within my project, I have implemented a [locale] directory to manage multiple language routes and utilize the params object to ...

Managing alerts in Python Selenium

I am encountering an issue while trying to handle a pop-up alert after a file upload. Despite using the code snippet below, I am receiving the error message shown. https://i.sstatic.net/Gqg8v.png wait.until(EC.alert_is_present()) driver.switch_to.alert() ...

Error: req.next is not a recognized function in node.js

I am completely stumped by this sudden issue that just appeared out of nowhere, with no changes in the code! TypeError: req.next is not a function The error is occurring at line 120. Here is the corresponding SQL query and the problematic line 120: // Set ...

streamlining form updates in vue

The code snippet provided is functional but unnecessarily complicated and lengthy. I am seeking a more efficient approach to achieve the desired outcome. <h6><label for="number">Change Number</label></h6> ...

The modification of a controller's attribute does not impact the view

Recently diving into Angular, I've encountered a small issue. Here's what's going on: After creating a module named "myMod", I proceeded to define a directive like so: myMod.directive("myDirective", function () { dir = { restri ...

Disable the click event for the last element displayed in ng-repeat

So I have this ng-repeat block that goes like this: <ol> <li class="pointer node-name" ng-click="myClick(node)" ng-repeat="node in myArray">{{node.name}}</li> </ol> It's all good and dandy, generating <li> elements ...

What is the reason for not encountering an error when reading an array beyond its index limit?

Recently, while working on a pre-existing website with JavaScript code, I made an interesting discovery. I noticed that the code was accessing array items in a unique way: var value = myArray[0, 1]; This seems to be retrieving the second item of the arr ...

Error message "Uncaught TypeError: Cannot read property 'domElement' of undefined" occurred in webgl-template.html at line 69 in Three.js

I found this interesting code on <!DOCTYPE html> <!-- saved from url=(0056)https://www.benzedrine.ch/vistaprint/webgl-template.html --> <html> <head> <meta http-equiv="Content-Type" content="text/html; charse ...

Incorporating Markers onto Google Maps using google-map-react

I've integrated the NPM package called google-map-react to build a Google Map with multiple markers. Inquiry: How do we include the default Google Maps markers on the map? Based on this Github discussion, it appears that accessing the internal Googl ...

When hovering over a specific div, it triggers a hover effect on a separate div

Currently, I am facing a dilemma: I have an effect triggered by hovering over one div, but I actually want the effect to be triggered when the cursor hovers over another div instead. To illustrate: <div id='mouse-hover-in-this-div'> bl ...

What happens when the `.push` command runs the "Undefined" function in jQuery - is it possible to execute a number instead?

My script is quite simple - I'm trying to use the push method to add the result of a function called dNumber into the variable named pattern. However, every time I try this, the result is always "undefined". Oddly enough, when I try pushing just plain ...

Utilize Express Node to display API information on HTML pages using Handlebars template

I'm seeking assistance in rendering data from an API to HTML using handlebars. I'm a bit puzzled on how to properly showcase the data on the webpage. Here's what I have so far: ROUTES FOLDER/FILE: const express = require('express&ap ...

Exploring the ‘ref’ feature in React alongside Material-UI

In my attempt to access input data through React's "ref" attribute on a TextField in Material-UI, I've encountered some difficulties. It doesn't seem straightforward to achieve this using the 'inputRef' or 'inputProps' me ...

Animating CSS Skill Bars as You Scroll

Is there a way to achieve a similar effect as seen here? I've tried implementing the code from this answer, but it's not entirely clear. The suggestion is to use this jQuery plugin, but I can't seem to make it work. I prefer using Foundation ...

Exploring the firestore section with vuefire for seamless access to methods

I am attempting to access a method in the firestore section of vuefire, but encountering the following error: vue-router.esm.js?8c4f:2257 TypeError: Cannot read property 'messagesWith' of undefined at eval (Chat.vue?62f3:214) This is the lin ...