How to create the JSON object for sending batch mail in mailgun

Viewed 81

I need to construct a json called recipient-variables dynamically given that I have 2 seperate arrays One for the emails and the other one for the first and the id.How will I be able to write the code for this in javascript

'recipient-variables': '{"alice@example.com": {"first":"Alice", "id":1}, "bob@example.com":{"first":"Bob", "id":2}}'

1 Answers

Assuming that your arrays look like this, based on the question:

emails = ["alice@example.com", "bob@example.com"]
firstids = [{"first": "Alice", "id": 1}, {"first": "Bob", "id": 2}]

You can write a for loop that goes through your items and puts them into a new object, using the email as a key, like this:

// Final result object
let obj = {};

for (let i = 0; i < emails.length; ++i) {
    obj[emails[i]] = firstids[i];
}
Related