Better way of editing certain fields in a json object?

Viewed 44

I have a javascript state object like this:

expFormErrors: { 
    position: false, 
    company: false, 
    dateStart: false, 
    dateEnd: false
}

I have an input field that is supposed to validate. My validation function goes as follows. Very simple.

function validateText(text, fieldError, fieldInStringFormat) {
    let minLength = 3;
    let maxLength = 30;
    let hasError = false;
    if(text.length < minLength || text.length > maxLength) {
        hasError = true;
    } else hasError = false;
    return {
        type: VALIDATE_TEXT,
        payload: { field: fieldInStringFormat, fieldError: hasError }
}

Ok, so it basically dispatches a redux store update. Inside the reducer I have a switch statement that updates the state according to what is put into the fieldInStringFormat parameter. Doing it this way seems to me, a huge amount of code to accomplish something simple... here is how it would look in the reducer.

switch(action.fieldInStringFormat){
case 'position':
    return {
        ...state,
        expFormError: action.payload.fieldError,
        expFormErrors: { 
            ...state.expFormErrors, 
            position: action.payload.fieldError }
        };
case 'company': 
    return {
        ...state,
        expFormError: action.payload.fieldError,
        expFormErrors: { 
            ...state.expFormErrors, 
            company: action.payload.fieldError 
        }
};
}

As you can see this is a whole lot of repeating code, which I believe is something nobody wants. 'Never repeat yourself' Say I had an object with 100 fields, typing all of that would be ridiculous.

Is there a better way of doing this? I tried looking up various JSON references but couldn't find any built in way of doing this.

What I imagined as a solution would be something like this:

return {
    ...state,
    expFormErrors: { 
        ...state.expFormErrors,
        [someParameterStringWhichWouldEqualTheWantedField]: action.payload.fieldError
1 Answers
Related