user526206
user526206

Reputation:

How to loop on array inside another arry in angualrjs

I have few records and i want to use foreach loop in controller

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

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

This is given an object in return as object containing inside of another array. Can someone suggest me how i can use foreach loop to get the code with this data.

Upvotes: 1

Views: 242

Answers (3)

Ikechi Michael
Ikechi Michael

Reputation: 489

Extending the Array prototype, allows you to do some awesome array manipulation in functional programming style easily. The following code should help.

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

First, you'd need to add these functions to your code.

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 like it, you should probably check out https://github.com/mykeels/ArraysJS There are a lot more functions like these there.

Upvotes: 0

SuperNova
SuperNova

Reputation: 27476

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

for (var i = 0; i< values.length ; i++){
   for (var j = 0; j< values[i].length ; j++){
      console.log(values[i][j])
   }
}
  • The native for loop is around 90% faster than angular.forEach.

  • Also angular.forEach loop can't break on a condition match.

Upvotes: 2

adrianj98
adrianj98

Reputation: 573

You just do another foreach inside

var codeList = [];

angular.forEach(values, function(value, key){
  angular.forEach(value, function(item, key){
      codelist.push(item.code);
   });
});

Upvotes: 2

Related Questions