user526206 user526206 - 7 months ago 33
Javascript Question

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.

Answer

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.