Search code examples
javascriptreactjssemantic-uireact-final-form

how to convert array to key value pair in react js?


I am using react-final-form with semantic-ui in my demo .I use multiple select dropdowns in my demo .

I convert multiselect dropdown to single select (I like the design having chip like structure) .

but my form data response incoming like this when I select any value. form response when user select any value

{
  "dropdown": [
    "ax"
  ]
}

expected response

{
      "dropdown": "ax"

    }

here is my code

https://codesandbox.io/s/musing-cerf-kg41n

I convert mutiselect to single select like this

onChange={(e, data) => {
          if (data.value && data.value.length > 1) {
            data.value.shift();
          }
          return input.onChange(data.value);
        }}

Solution

  • You can mutate the values on submit to fit your needs like this:

     const onSubmit = async values => {
      await sleep(300);
       const transformedValue = {
           dropdown: values.dropdown[0]
       } 
       window.alert(JSON.stringify(transformedValue , 0, 2));
     };
    

    This will result in the desired outcome and keeps the chip view.