title: Updating an object in an array if the object exists
body: <p>I am trying to take an array of objects, check if the key exists in the array, and replace the value if the key exists, and if the key does not exist, I would like to add the key-value pair to the array. I thought it would be simple, but I am having trouble. The idea is to not have a situation where two objects with the same key exist in the array.</p>
  <p>The array looks like...</p>
  <pre><code>let state = [{spouse: true}, {age: 50}, {numOfChildren: 2}, etc..]
  </code></pre>
  <p>My code is as such</p>
  <pre><code>const reducer = (state, action) =&gt; {
   switch(action.type){
      case &quot;ADD_SPOUSE&quot;:
          // take state array
          // find the index of the object that has the correct key if it exists
          if (stateArrayHasObject) {
              // replace the current object {spouse: action.spouse} with the new value
              return state;
          } else {
              return ([...state, {spouse: action.spouse}]);
          }
  </code></pre>
  <p>In a truthy situation, how to I update the value of the object in the state array?</p>
  <p>I checked <a href="https://stackoverflow.com/questions/37524969/check-if-an-object-exists-in-an-array">this answer</a>, <a href="https://stackoverflow.com/questions/1098040/checking-if-a-key-exists-in-a-javascript-object">this answer</a>, <a href="https://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object">and this answer</a>, which don't really provide an efficient way of finding and replacing an object in an array if the object key exists in the array.</p>