分组在AngularJS中的复杂对象上

时间:2015-06-25 10:26:59

标签: angularjs arrays json sorting

我有一个包含任务员工任务的数组,它看起来像这样:

$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 the world", project:"Destruction"
      },
      date: {
        day:"02/01", year:"1985"
      }
    }
];

我想按员工分组,因为有这样的事情:

$scope.assignmentsByEmployee = [
    { //First item
      id:"1", 
      firstname:"John",
      lastname:"Rambo",
      missions: [
        {
          name:"Kill everyone",
          date:"01/01",
          year:"1985"
        },
        {
          name:"Save the world",
          date:"02/01",
          year:"1985"
        }
      ]
    },
    { //Second item
      id="2",
      firstname:"Luke",
      lastname:"Skywalker",
      missions: [
        name:"Find daddy",
          date:"65/45",
          year:"1000000"         
      ]
   }
];

他们是一个简单的方法吗?我用双forEach尝试了一些东西,但它让我无处可去。

希望我能理解:)

谢谢!

1 个答案:

答案 0 :(得分:2)

您应该能够遍历赋值数组并在员工ID上创建“键控数组”(这意味着在JavaScript中使用对象)。然后你只需要填写任务阵列。

这样的东西
// initialise a holding object
var assignmentsByEmployee = {};

// loop through all assignemnts
for(var i = 0; i < $scope.assignments.length; i++) {
    // grab current assignment
    var currentAssignment = $scope.assignments[i];
    // grab current id
    var currentId = currentAssignment.employee.id;

    // check if we have seen this employee before
    if(assignmentsByEmployee[currentId] === undefined) {
        // we haven't, so add a new object to the array
        assignmentsByEmployee[currentId] = {
            id: currentId,
            firstname: currentAssignment.employee.firstname,
            lastname: currentAssignment.employee.lastname,
            missions: []
        };
    }

    // we know the employee exists at this point, so simply add the mission details
    assignmentsByEmployee[currentId].missions.push({
        name: currentAssignment.task.name,
        date: currentAssignment.date.day,
        year: currentAssignment.date.year
    });
}

这些留下assignmentsByEmployee作为对象,但您可以简单地通过它,并在需要时将其转换回数组。 E.g:

$scope.assignmentsByEmployee = [];
for(var employeeId in assignmentsByEmployee) {
    $scope.assignmentsByEmployee.push(assignmentsByEmployee[employeeId]);
}