javascript - Better way of editing certain fields in a json object? -


i have javascript state object this:

expformerrors: {      position: false,      company: false,      datestart: false,      dateend: false } 

i have input field supposed validate. validation function goes follows. 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, dispatches redux store update. inside reducer have switch statement updates state according put fieldinstringformat parameter. doing way seems me, huge amount of code accomplish simple... here how in 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 can see whole lot of repeating code, believe nobody wants. 'never repeat yourself' had object 100 fields, typing of ridiculous.

is there better way of doing this? tried looking various json references couldn't find built in way of doing this.

what imagined solution this:

return {     ...state,     expformerrors: {          ...state.expformerrors,         [someparameterstringwhichwouldequalthewantedfield]: action.payload.fielderror 

the term want computed property keys. need:

return {   ...state,   expformerrors: {     ...state.expformerrors,     [action.fieldinstringformat]: action.payload.fielderror   } }; 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -