When I try to return a literal object with Arrow Function
, it gives an error:
var items = [1, 2, 3].map( i => {valor: i, data: new Date() })
How to get around this in Javascript?
When I try to return a literal object with Arrow Function
, it gives an error:
var items = [1, 2, 3].map( i => {valor: i, data: new Date() })
How to get around this in Javascript?
You can put the object in parentheses.
So:
var items = [1, 2, 3].map( i => ({valor: i, data: new Date()}))
console.log(items)
This error occurs because JS does not assign a value to a variable using a colon ( :
), which is what you are trying to do within the function.
.map
it seems to me that you want to return an array of objects from the array mapped, so you can use return
with the values of the% keys {}
because the other keys delimit the body of the function:
var items = [1, 2, 3].map( i => { return {valor: i, data: new Date()} })
console.log(items)