Muffin
Muffin

Reputation: 791

Double loop to get Ng-options

I want to get all the tasks name as task id, where array of tasks are stored in array of groups. I am trying to get it in ng-options directive of angularJS. Here is http://jsfiddle.net/753YB/16/ link for quick edit. thanks in advance! I know in single array it is task.Id as task.Name for task in Tasks but my tasks are nested in groups so I need tasks in all group.

$scope.Groups = [{
        Name: 'a1',
        Id: 1,
       Tasks:[{Name: 'Some Name' Id: 1},{Name: 'Some Name 2' Id: 2}]
    }, {
        Name: 'c2',
        Id: 2,
        Tasks:[{Name: 'Some Name 3' Id: 3},{Name: 'Some Name 4' Id: 4}]
    },
       {
        Name: 'c2',
        Id: 3,
        Tasks:[{Name: 'Some Name 3' Id: 5},{Name: 'Some Name 4' Id: 6}]
    }];

Upvotes: 1

Views: 1112

Answers (1)

Michael Kang
Michael Kang

Reputation: 52837

You can flatten your data structure with the following function:

function flattenArray(array, fn)  {
   var output = [];
   for(var i = 0; i < array.length; ++i) {
      var result = fn(array[i]);
      if (result) 
         output = output.concat(result);
   }
   return output;
}

Call the function by passing it an array and an item callback. The callback returns the sub-array.

$scope.Groups = flattenArray(groups, function(item) { 
     return item.Tasks;
}); 

Demo Fiddle

Upvotes: 3

Related Questions