0

This is a silly question, but I just stuck here.

Premise

let groups = [
  {id: 1, name: '123'},
  {id: 2, name: '456'}
]

And I want to output this

[
  {value: 1, label: '123'},
  {value: 2, label: '456'}
]

I don't understand why it causes an error.

groupOptions = groups.map(item =>
  {value: item.id, label: item.name}
)
1
  • You forgot to add parenthesis inside map after arrow.! Commented Aug 23, 2017 at 9:01

3 Answers 3

1

Wrap the returned object into (). Withour () curly braces will be considered to be the arrow function’s body and inside the body your expressions are invalid.

let groups = [
  {id: 1, name: '123'},
  {id: 2, name: '456'}
]

var groupOptions = groups.map(item =>
  ({value: item.id, label: item.name})
);

console.log(groupOptions);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation.
0

let groups = [
  {id: 1, name: '123'},
  {id: 2, name: '456'}
]
var output = groupOptions = groups.map(item =>
  {return {value: item.id, label: item.name}}
)

console.log(output);

You need to wrap your map callback code in {}:

let groups = [
  {id: 1, name: '123'},
  {id: 2, name: '456'}
]
groupOptions = groups.map(item =>
  {return {value: item.id, label: item.name}}
)

1 Comment

Thanks, but it seems the return is not necessary?
0

It's a bit more clean if you destructure the item argument of your map callback:

let groups = [
  {id: 1, name: '123'},
  {id: 2, name: '456'}
]
var output = groupOptions = groups.map(({id,name}) => 
    ({value:id, label:name})
);

// or you can do the mapping right in the arguments:

var output = groupOptions = ggroups.map(({id:value,name:label}) =>
    ({value, label})
);

1 Comment

Thanks for the answer, but I want it to be simpler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.