Search code examples
javascriptdictionaryobjectgoogle-apps-scriptsyntax

Why does creating an array of objects within a map call result in a syntax error with the colons?


I wrote a function in Google Apps Script for getting the date and subject of all emails with a given label in Gmail. However, when I try to store each result as an object, I get a SyntaxError: unexpected token ':' error. If I create a list to store each pair of data, then there is no problem, but I want to have each be a key-value pair so the data is accessible by lable.

Here is a simple version of the function showing what works and what doesn't:

function displayEmailParts() {
    var labelName = 'foo';
    var threads = GmailApp.getUserLabelByName(labelName).getThreads();
    var initialMessages = threads.map((x) => x.getMessages()[0]);
    
    // this works:
    var messageParts = initialMessages.map(
        (x) => [x.getSubject(), x.getDate()]
    );

    // this gives a syntax error:
    var messageParts = initialMessages.map(
        (x) => {subject: x.getSubject(), date: x.getDate()}
    );

    return messageParts
}

is there any reason why having an object as the output of a map call over an array is not valid?


Solution

  • You need to wrap it in () so js knows that it is returned value rather than just function block. E.g.

    () => ({yourProp: val})