4

I have an array of checkbox rendered as:

<form>
  {items.map(item => {
    <Field component="input" 
           type="checkbox"
           name=`items.{item.id}`
  })}
</form>

This gives me values as an Array:

 {
           //index: 0,   1,     ,…, 120, 121, …    ,231, …                      
     item: [undefinded,undefined,…,true,undefined,…,true,undefined,…]
 }

Instead I would prefer an Object, (mainly to avoid a large array being created):

{
    120: true,
    131: true,
    165: false 
}

Is there a way to force redux-form output object when itemId is integer.

Note: If itemId is passed as string then redux-form does return an Array.

Similar post but solution does not work with redux-form 7.

0

3 Answers 3

1

I came across this while looking for a solution to the same problem.

What eventually worked for me is to initialize the object when passing the initial values to the form

const ItemsForm = ({ items }) => {
    return <form>
        {items.map(item => {            
            <Field component="input"
                type="checkbox"
                name={`items.${item.id}`} />
        })}
    </form>
}

export default reduxForm({
    form: 'itemsForm'
})(ItemsForm)

Initialize the form like this:

<ItemsForm initialValues={{items: {}}} />
Sign up to request clarification or add additional context in comments.

Comments

0

You could just use the filter function when you're mapping the form field from the state:

checkboxArray.filter(checkbox =>{
    return checkbox; // if its undefined, it'll get dropped from the array
});

Associative arrays and objects are actually identical in Javascript, so no more work is needed, so having filtered out all of the undefined items in the array gets you the object you're looking for.

Comments

0

issue is that the field name is a number. try prefixing it.

instead of '102' >> 'myField_102'

Comments

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.