简体   繁体   中英

How do I use the Javascript map function with object literals?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM