-1

I wanted to do a very basic mapping to JS Object from some array of integers;

[1,2,3,4,5].map(val => {num: val})
           .forEach(result => console.log(result));

But as you can see it returns all undefined, is it due to the usage of curly brackets that is confused with lambda's body part? Using a boring syntax works though;

[1,2,3,4,5].map(function(val) {return {num: val}})
           .forEach(result => console.log(result));

Also this;

[1,2,3,4,5].map(val => {return {num: val}})
           .forEach(result => console.log(result));

Is there no way to achieve what I am trying to do with lambda notation? Since the sleeker the better IMO

buræquete
  • 14,226
  • 4
  • 44
  • 89
  • 2
    This is most certainly a duplicate, but the tl;dr version is - wrap your object literal in parenthesis `[1,2,3,4,5].map(val => ({num: val}))` – Damon Mar 14 '17 at 01:21
  • @Damon oh, I couldn't find the exact question, that is why wanted to ask, sorry~ – buræquete Mar 14 '17 at 01:28
  • 1
    no worries, wasn't reprimanding you or anything - the comment was more because I knew it would be closed as a duplicate but was too lazy to look for the "original" - it's a common problem :) – Damon Mar 14 '17 at 01:28
  • 1
    @Damon yeah I did search but couldn't find, btw however obsolete this comment is, I love the image in your profile, made me chuckle! – buræquete Mar 14 '17 at 01:33

1 Answers1

3

This will work.

[1,2,3,4,5].map(val => ({num: val}))
       .forEach(result => console.log(result));
jessegavin
  • 74,067
  • 28
  • 136
  • 164