Double loop to get Ng-options

痴心易碎 提交于 2019-12-11 13:23:44

问题


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}]
    }];

回答1:


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



来源:https://stackoverflow.com/questions/24860452/double-loop-to-get-ng-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!