Search code examples
javascriptarraysobjectgoogle-apps-script

How to create an array of objects in google script using object.map


I am trying to create an array of objects derived from a list of users and have the following line of code:

var usersEmail=group.map((user)=>{eMail : user.email, rOle : user.role});

the ':' in 'rOle : user.role' causes an error of unexpected ':' when I try to save the code. If I use this code:

var usersEmail=group.map((user)=>[user.email, user.role]);

I create an array of 2 element array's, which works but is not as nice as I would like. My final attempt was this:

var usersEmail=group.map((user)=>[{eMail : user.email, rOle : user.role}]);

which creates an array of single element arrays each of which contain the correct object. I feel that what I want to do is entirely possible, but I just don't have the right structure to do so.

Grateful for any help.


Solution

  • I think this is what you are looking for :

    var usersEmail = group.map((user)=> ({eMail : user.email, rOle : user.role}));
    

    they are needed here because you are using an inline (anonymous) function, so you need something to show that this is indeed an object and not a function.

    You could also do it this way :

     var usersEmail = group.map((user)=> {
        return {eMail : user.email, rOle : user.role};
     });