5

I'm having a problem writing some Javascript code. I'm trying to use the map function to create a new array. Here's my code:

[1,2,3].map(m => {'id': m})

I expected that the result would be:

[
    {'id': 1},
    {'id': 2},
    {'id': 3}
]

Instead, I get an error that says "Uncaught SyntaxError: Unexpected token :"

Can someone tell me what I'm doing wrong?

user2023861
  • 8,030
  • 9
  • 57
  • 86
  • See https://stackoverflow.com/questions/40348171/es6-map-an-array-of-objects-to-return-an-array-of-objects-with-new-keys/40348205#40348205 – Nenad Vracar Jan 14 '19 at 17:02
  • 3
    Just my 2 cents (opinion) comment here on the downvotes on the question. While it's actually a duplicate and I voted to close as such, the question is clear, has MCVE, current error and expected output, and searching for it is not that obvious when you haven't fell into this trap. The phrasing of the title is different from dupe target, and I think this question should not be deleted because it helps searchability for those who encounter the same problem. So, I don't think it deserves the downvotes it gets (at least for being a duplicate), IMHO. – Pac0 Jan 14 '19 at 17:07
  • 1
    @Pac0, I don't mind if this question gets downvotes. I know it's a low-quality question. I'm just happy that tigerswithguitars gave me an answer. I don't have to pull out my hair anymore. – user2023861 Jan 14 '19 at 17:13

1 Answers1

15

The lambda thinks your object is a function body.

[1,2,3].map(m => ({'id': m}))

Adding some extra brackets will tell it it's an object literal.

tigerswithguitars
  • 2,497
  • 1
  • 31
  • 53