0

Am having two sets of arrays :

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

I wanted to generate an array of objects by combining the employees and tasks like a many to many relationship.The length of $scope.selectedEmployees and $scope.selectedTasks may vary :

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

The method I tried:

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

But i'm not able to get the required format.Any help will be grateful.

2
  • You forgot the < in your second for loop : j<$scope... Commented May 20, 2015 at 12:21
  • And it should be selectedTasks and not selectedIntervention Commented May 20, 2015 at 12:23

1 Answer 1

2

http://jsfiddle.net/zuv8y9wk/

Issues were a missing < and instead of selectedTasks, selectedIntervention was used.

See working code below:

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.