Search code examples
javascriptarraysnode.jshashsendgrid-api-v3

Trying to generate an array of hashes in Node from model object


In order to send an email to multiple recipients via SendGrid API v3 using a dynamic template, I need to pass an email parameter like:

 "to":[
        {
           "email":"example1@example.com"
        },
        { "email": "example2@example.com"
        }
     ],

Obviously I am not wanting to hard code these email addresses s.t. they are dynamic.

I currently generate a list of emails with this code:

  // loop through users
  var users = group.user;
  var emails = users.map(function (obj) {
    return obj.email;
  });

Which returns eg:

[ 'example1@example.com', 'example2@example.com' ]

How do I return instead the array of hashes:

[
        {
           "email":"example1@example.com"
        },
        { "email": "example2@example.com"
        }
     ]

Solution

  • Maybe what you are trying to say is hashmap, not hashes, if not, I don't understand the question.

    To achieve the lists of maps that you mention, your code should be something like:

    // loop through users
      var users = group.user;
      var emails = users.map(function (obj) {
        return {email: obj.email};
      });
    

    Every item of the list would have email as key, and the email as value.

    What is a hash: https://en.wikipedia.org/wiki/Hash_function

    What is a hash table: https://en.wikipedia.org/wiki/Hash_table

    What is a js object: https://www.w3schools.com/js/js_objects.asp