arrays - Group by on a complex object in AngularJS -
i've array contains assignments of employees on tasks, looks this:
$scope.assignments = [ { employee: { id:"1", firstname:"john", lastname:"rambo" }, task: { name:"kill everyone", project:"destruction" }, date: { day:"01/01", year:"1985" } }, { employee: { id:"2", firstname:"luke", lastname:"skywalker" }, task: { name:"find daddy", project:"star wars" }, date: { day:"65/45", year:"1000000" } }, { employee: { id:"1", firstname:"john", lastname:"rambo" }, task: { name:"save world", project:"destruction" }, date: { day:"02/01", year:"1985" } } ];
i group employee, having this:
$scope.assignmentsbyemployee = [ { //first item id:"1", firstname:"john", lastname:"rambo", missions: [ { name:"kill everyone", date:"01/01", year:"1985" }, { name:"save world", date:"02/01", year:"1985" } ] }, { //second item id="2", firstname:"luke", lastname:"skywalker", missions: [ name:"find daddy", date:"65/45", year:"1000000" ] } ];
is simple way ? tried double foreach
, leads me nowhere.
hope i'm understandable :)
thanks !
you should able loop through assignments array , create 'keyed array' (which means using object in javascript) on employee id. fill missions array required.
something like
// initialise holding object var assignmentsbyemployee = {}; // loop through assignemnts for(var = 0; < $scope.assignments.length; i++) { // grab current assignment var currentassignment = $scope.assignments[i]; // grab current id var currentid = currentassignment.employee.id; // check if have seen employee before if(assignmentsbyemployee[currentid] === undefined) { // haven't, add new object array assignmentsbyemployee[currentid] = { id: currentid, firstname: currentassignment.employee.firstname, lastname: currentassignment.employee.lastname, missions: [] }; } // know employee exists @ point, add mission details assignmentsbyemployee[currentid].missions.push({ name: currentassignment.task.name, date: currentassignment.date.day, year: currentassignment.date.year }); }
these leaves assignmentsbyemployee
object, can foreach through , convert array if required. e.g:
$scope.assignmentsbyemployee = []; for(var employeeid in assignmentsbyemployee) { $scope.assignmentsbyemployee.push(assignmentsbyemployee[employeeid]); }
Comments
Post a Comment