How to return a literal object in an Arrow Function?

Asked

Viewed 240 times

3

How much I try to return a literal object with Arrow Function, makes a mistake:

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

How to get around this in Javascript?

2 answers

9


You can place the object in parentheses.

Thus:

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

console.log(items)

4

This error is because the JS does not assign value to a variable using two-points (:), which is what one is trying to do within the function.

Using .map it seems to me that you want to return an array of objects from the mapped array, so you can use a return with the values inside of keys {} due to other keys delimiting the function body:

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

  • You can send a i => Object.create({ ... }) also, but gives sadness just thinking, kkkk

  • For eh rsrs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.