How to return a literal object in an arrow function?

3

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?

    
asked by anonymous 05.11.2018 / 19:52

2 answers

9

You can put the object in parentheses.

So:

var items = [1, 2, 3].map( i => ({valor: i, data: new Date()}))

console.log(items)
    
05.11.2018 / 20:00
4

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.

Using .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)
    
05.11.2018 / 20:00