Reputation: 445
Resume: For each value selected in a multi-select field, a function is called and add the value to a string. All I want is to add it as a Object into a array. Example:
1 options selected:
Current:
"selected01"
Desired:
[ { "value": "selected01"} ]
2 options selected:
Current:
"selected01, selected02"
Desired:
[ {"value": "selected01"}, {"value":"selected02"}]
Full explanation:
I have a function, that receives a String and add it to the state the value. Example:
handleSelectChange (value) {
this.setState({ value })
}
So imagine you have a multi selectable field with three choices and select two of them.
It will call:
onChange={this.handleSelectChange}
The state will be then:
state.value: 'selected01, selected02'
In case you select one more:
state.value: 'selected01, selected02, selected03'
But what I'm trying to do is to have a Array with 3 objects:
Object:
[
{"value": "select01"},
{"value": "select02"},
{"value": "select03"}
]
Another way to see the desired output (console.log):
state: [3]
[0]: Object
[1]: Object
[2]: Object
Any ideas?
Upvotes: 1
Views: 14465
Reputation: 445
Answer is:
handleSelectChange (value) {
this.setState({value})
let valuesArr = value.split(',')
let valuesArrObj = []
valuesArr.forEach((val) => {
valuesArrObj.push({
[val]: val
})
})
Upvotes: 1
Reputation: 418
You can call this.getState() add your selection and then do a this.setState(). For example (using lodash https://lodash.com/docs/4.17.4#concat):
this.setState(_.concat(this.getState(), { value }))
Upvotes: 0