how to map an array to another array with different values (angularJs)
11,067
A solution could be:
var list = $scope.users.map(function(user) {
return {
name: user.firstName + ' ' + user.lastName,
value: {
registration: user.registrationNumber,
first: user.firstName,
last: user.lastName
}
};
});
Explanation
Array.map() iterates over the existing array and returns a new modified one.
So you have to use map
on $scope.users
and for each user
you want to return a new object. In each iteration you have access on each user
. The new objects will be stored inside list
which will be an array.
Author by
jeremy
Updated on June 19, 2022Comments
-
jeremy almost 2 years
Currently I am trying to use an existing array to map it to another array in order to match what the server wants.
for example...
I have an array:
$scope.users = [{ "firstName": "john", "middleName": null, "lastName": "doe", "registrationNumber": "334" }, { "firstName": "paul", "middleName": null, "lastName": "dean", "registrationNumber": "223" }, { "firstName": "andrew", "middleName": null, "lastName": "mac", "registrationNumber": "132" } ]
however I want it to look like this...
[{ name: "john doe", value: { registration: 334, last: "doe", first: "john" } }]
So what I've been doing is something like this to map it out...but it only gets the first one.
var list = [{ name: $scope.users[0].firstName + ' ' + $scope.users[0].lastName, value: { registration: $scope.users[0].registrationNumber, first: $scope.users[0].firstName, last: $scope.users[0].lastName } }];
I tried to use
angular.forEach
to get all the list and push it...but hasn't really worked too well yet... any help would be great!