1

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?

6
  • this.setState(value.split(", ")); Commented Jul 16, 2017 at 11:46
  • maybe I'm not getting the question but won't a simple value.split(',') do the trick? Commented Jul 16, 2017 at 11:46
  • if you want to convert that string into array of object, what will be the key?? if you want to convert into array of strings then use split(','), you will get ['a', 'b', 'c'] Commented Jul 16, 2017 at 11:48
  • I don't see how the split will get my value and create an Object with the value. The selected field are being added to a String, and I need it to have added to a new Object. Current with one option: "selected01" Desired: [ { "selected01"} ] Commented Jul 16, 2017 at 11:50
  • @LucasOliveiraSilva that object should have the key, what will be the key that you want it will be [{key: 'selected01'}, {key: 'selected02'}]. Commented Jul 16, 2017 at 11:55

3 Answers 3

1

Answer is:

handleSelectChange (value) {
  this.setState({value})
  let valuesArr = value.split(',')
  let valuesArrObj = []
  valuesArr.forEach((val) => {
    valuesArrObj.push({
      [val]: val
    })
})
Sign up to request clarification or add additional context in comments.

Comments

0

use this.setState() for insert element, and this.getState() for get element

for any info go here

1 Comment

This is not related to my question.
0

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 }))

1 Comment

There are many ways. I only provided one possible example solution.

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.