Search code examples
javascriptecmascript-6javascript-objects

Shorter way to update object properties in JavaScript?


I have a list of user submissions on different questions and whenever it is being updated, I have several properties I'm updating. I'm wondering if there is a better way perhaps by destructing or spreading to make this cleaner/shorter? Here's what I'm doing at the moment, I've lessened the number of properties in the example, but in the actual project I am updating around 5-6 properties one by one and I felt it is a little repetitive to set it one by one.

updateSubmission ( id, type, value ) {
  const obj = state.submission.filter( el => el.id === id )[ 0 ]
  obj.type = type
  obj.value = value
}

Solution

  • Use .find to find the single matching object instead of .filter, then you can Object.assign both properties with shorthand:

    updateSubmission ( id, type, value ) {
      Object.assign(
        state.submission.find( el => el.id === id ),
        { type, value }
      );
    }