Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  40] [ 4]  / answers: 1 / hits: 20958  / 9 Years ago, tue, may 5, 2015, 12:00:00

I have two arrays, Users and Employments like so:



Users       = [{id:1, name: ryan}, {id:2, name:Julie}]
Employments = [{user_id: 1, title: manager}, {user_id: 2, title: Professor}]


I'd like to display the Employments array in an ng-repeat like so:



<li ng-repeat=employment in Employments>
{{employment.user.name}}
</li>


How do I map the Users array to the Employments array?


More From » arrays

 Answers
460

If you want the employee name to get displayed based on id, the simplest way is just pass that id to a function and return the name, like as shown below



Working Demo



html



<div ng-app='myApp' ng-controller=ArrayController>
<li ng-repeat=employment in Employments>{{getEmployeeName(employment.user_id)}}
</li>
</div>


script



var app = angular.module('myApp', []);
app.controller('ArrayController', function ($scope) {
$scope.Users = [{
id: 1,
name: ryan
}, {
id: 2,
name: Julie
}];

$scope.Employments = [{
user_id: 1,
title: manager
}, {
user_id: 2,
title: Professor
}];

$scope.getEmployeeName = function (empId) {
for (var i = 0; i < $scope.Users.length; i++) {
if ($scope.Users[i].id === empId) {
return $scope.Users[i].name;
}
};
};
});


UPDATE 2



If you want to embed the User array in the Employments array, try the following stuff



$scope.Users = [{id: 1, name: ryan}, {id: 2, name: Julie}];

$scope.Employments = [{user_id: 1, title: manager},
{user_id: 2, title: Professor}
];


code for flattening Employments array by adding User properties



angular.forEach($scope.Users, function (user, userIndex) {
angular.forEach($scope.Employments, function (employee, employeeIndex) {
if (employee.user_id === user.id) {
employee.name = user.name;
}
});
});


Output



$scope.Employments = [ { user_id: 1, title: manager, name: ryan }, 
{ user_id: 2, title: Professor, name: Julie }
]


Working Demo



UPDATE 3



Code for making a nested employee structure like as shown below from $scope.Users and $scope.Employments



$scope.employees = [];
angular.forEach($scope.Employments, function (employee, employeeIndex) {
var employeeObject = {};
employeeObject.title = employee.title;
angular.forEach($scope.Users, function (user, userIndex) {
if (employee.user_id === user.id) {
employeeObject.user = user;
}
});
$scope.employees.push(employeeObject);
});


Output



[ { title: manager, user: { id: 1, name: ryan } }, 
{ title: Professor, user: { id: 2, name: Julie } }
]


Working Demo


[#66747] Saturday, May 2, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byrondonavanc

Total Points: 675
Total Questions: 107
Total Answers: 105

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
byrondonavanc questions
;