Return Ibject From Javascript Lambda
Let’s say we have an array of strings like this:
vals1 = ["A", "B", "C", "D"]
We want to run the array through a map function to get the structure:
[ { _id: 'A' }, { _id: 'B' }, { _id: 'C' } ]
…and so we try writing a map function like this:
vals2 = vals1.map(e => {_id: e})
//Returns: [ undefined, undefined, undefined ]
It seems odd at first, but Javascript interprets the squiggly brackets as a function, so the executing code looks something like this:
vals2 = vals1.map(function(e) {_id: e})
//Returns: [ undefined, undefined, undefined ]
By writing a function body with the first pair of squiggly brackets and using another pair of brackets to indicate an object, we can achieve what we are looking for:
vals2 = vals1.map(e => {return {_id: e}})
//Returns: [ { _id: 'A' }, { _id: 'B' }, { _id: 'C' } ]
This can also be written using anonymous functions as:
vals2 = vals1.map(function(e) {return {_id: e}})
//Returns: [ { _id: 'A' }, { _id: 'B' }, { _id: 'C' } ]