one liner to remove a n element from an object

Viewed 236

This is related to storing manipulated objects in react, but is also a general javascript question.

In react, you usually take a current state object, and add to it like so:

setFormErrors({...formErrors, agreeToRefund: 'Some message'})

where formErrors and setFormErrors is what comes out of useState() hook.

To do a delete, you have to the more verbose:

const newFormErrors = {...formErrors};
delete newFormErrors.agreeToRefund;
setFormErrors(newFormErrors)

Which is a little tedious. Is there a more abbreviated 1 liner to do this?

3 Answers

In 2 statements, yes, but not 1.

const {agreeToRefund , ...newFormErrors} = formErrors;
setFormErrors(newFormErrors)

But if it were me, I'd change the user of formErrors to understand a property value of null or '' instead of removing it from state entirely.

setFormErrors({...formErrors, agreeToRefund: null})

Or you can play with map and comma operator if you do not mind:

box it in a array so you can map over it to delete what you want then pop it back.

setFormErrors([{...newFormErrors}].map(obj=> (delete obj.agreeToRefund,obj)).pop())

let formErrors={fistnam:'error',lastname:'error again'}
console.log('formErrors:',formErrors)
let newFormErrors={...formErrors, agreeToRefund: 'Some message'}
console.log('newFormErrors:',newFormErrors)
let noagreeToRefund=[{...newFormErrors}].map(obj=> (delete obj.agreeToRefund,obj)).pop()//?
console.log('noagreeToRefund:',noagreeToRefund)

One option is to create a utility function (probably exported in a util library)

function newObjWithoutProperty(obj, prop) {
  const newObj = { ...obj };
  delete newObj[prop];
  return newObj;
}

then it becomes:

      setFormErrors(newObjWithoutProperty(formErrors, 'agreeToRefund'));
Related