javascript

时间:2015-05-20 12:18:08

标签: javascript arrays angularjs multidimensional-array

我有两组数组:

$scope.selectedEmployees = ["1001", "1002"];
$scope.selectedTasks = ["Task1", "Task2"];

我想通过组合员工和任务来生成一个对象数组,例如多对多的关系。$ scope.selectedEmployees和$ scope.selectedTasks的长度可能会有所不同:

newArray=[
    {
        "empId": 1001,
        "task": "Task1"
    },
    {
        "empId": 1001,
        "task": "Task2"
    },
    {
        "empId": 1002,
        "task": "Task2"
    },
    {
        "empId": 1002,
        "task": "Task2"
    }
]

我试过的方法:

 var newArray=[];
         for (var i = 0; i <$scope.selectedEmployees.length; i++) {
           for (var j = 0; j <$scope.selectedTasks .length; j++) {
    newArray.push({"empId":$scope.selectedEmployees[i],
                  "task":$scope.selectedIntervention[j]
                 })
                   }
                }

但是我无法获得所需的格式。任何帮助都会感激不尽。

1 个答案:

答案 0 :(得分:2)

http://jsfiddle.net/zuv8y9wk/

而不是selectedTasks,使用了selectedIntervention

var $scope = {};
$scope.selectedEmployees = ["1001", "1002"];
$scope.selectedTasks = ["Task1", "Task2"];
var newArray = [];
for (var i = 0; i < $scope.selectedEmployees.length; i++) {
    for (var j = 0; j < $scope.selectedTasks.length; j++) {
        newArray.push({
            "empId": $scope.selectedEmployees[i],
            "task": $scope.selectedTasks[j]
        })
    }
}
console.log(newArray)