I am trying to convert an arrow function into a regular function
this piece of code:
let rating = watchList.map( (item) => ({"title":item["Title"], "rating":item["imdbRating"]}) )
like so:
let rating = watchList.map( function (item) {
"title":item["Title"], "rating":item["imdbRating"]
})
while I thought these two are equivalent, I am getting this message
SyntaxError: unknown: Unexpected token, expected
You are lacking return. When you pass in a custom function for the Array.map method, you will need to return a value for that function.
let rating = watchList.map(function(item) {
return {"title":item["Title"], "rating":item["imdbRating"]};
})
Nonetheless, it is more useful to use the arrow functions, as arrow functions seems more concise, and allows you to access this within it.
In arrow function any expression after => become implicit return of function.
In regular functions you need to use return keyword.And also warp your properties in {}
let rating = watchList.map(function(item){
return {"title":item["Title"], "rating":item["imdbRating"]};
}
You can also shorten your code by using Parameter destructuring.
let rating = watchList.map(function({Title:title,imdbRating:rating}){
return {"title":Title, "rating":imdbRating};
}
Or you could name to properties while destuctruing.
let rating = watchList.map(function({Title:title,imdbRating:rating}){
return {title,rating};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With