4

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!

1
  • 2
    ever heard of Array.map? Commented Jul 24, 2017 at 20:50

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

And support for Array.map has been around for years now (watch out for < IE10) caniuse.com/#search=map
Is it possible to use .map without creating a new array?

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.