7月 13, 2021

Javascript object array map problem

 for an array of objects, to extract fields and map into a simpler array, 

object : SomeObject = {a: 1, b:2, c:3}

array: SomeObject[] = ...


do:

newArray = array.map(x => ({x.a, x.b}))


instead of

newArray = array.map(x => {x.a, x.b})

 

Otherwise it doesn't work.

 

Reference:

 

"What you need to do is force the parser to treat the object literal as an expression so that it's not treated as a block statement. The trick is to add parentheses around the entire body: "


https://mariusschulz.com/blog/returning-object-literals-from-arrow-functions-in-javascript

沒有留言:

張貼留言