0

I'm using react-select and want to loop through an object to represent it as the select's value and label:

// Inside the component's render:

var myVar = [
  this.props.foo.forEach(function(a){
    {value: a.name, label: a.name} // line 83
  })
];

//return

<Select ref="stateSelect" options={myVar} simpleValue clearable={this.state.clearable}
  name=""
  value={this.state.bar} onChange={this._myFunc} 
/>

this._myFunc is not relevant for this question. I want to get something like this:

var myVar = [
  {value: "hello", label: "world"},
  // the list goes on
];

With the above code, I got:

Parse Error: Line 83: Unexpected token :

I'm not that strong with JavaScript to figure out this solution but is this possible? Links to read up on?

1
  • 1
    { ... } is considered as block here. Probably you need someObj = {value: a.name, label: a.name} Commented Jul 7, 2016 at 13:43

2 Answers 2

2

If you intend to initialize myVar with an array of objects from this.props.foo then try

var myVar = this.props.foo.map(function(a){
    return {value: a.name, label: a.name} ;
});
Sign up to request clarification or add additional context in comments.

5 Comments

Failed propType: Invalid prop option of type array supplied to Option, expected object. Check the render method of Select.
@Sylar are you still getting Parse Error: Line 83: Unexpected token : ? what were you expecting to get as an output from this statement?
Getting error as in my first comment. In my question where the list goes on that's what works but I need the value and label from an array.
@Sylar can you share a fiddle?
SORRY! I was wrapping your answer inside: var myVar = [ //your answer] It works. Thanks
1

The best is loop in render fct like this:

render (){
 return (
  <div>
   <Select
     ref="stateSelect"
     options={
      this.props.foo.map( (a) => {name: a.name, label: a.name} )
     }
     simpleValue
     clearable={this.state.clearable}
     name=""
     value={this.state.bar}
     onChange={this._myFunc} 
   />
  </div>);
}

2 Comments

Is this es6? "Fat arrow"? Maybe useful in other projects.
Yes es6 with jsx. You can use in es5 map( function(a) { return {name: a.name, label: a.name} })

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.