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.
The array looks like...
let state = [{spouse: true}, {age: 50}, {numOfChildren: 2}, etc..]
My code is as such
const reducer = (state, action) => {
switch(action.type){
case "ADD_SPOUSE":
// 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}]);
}
In a truthy situation, how to I update the value of the object in the state array?
I checked this answer, this answer, and this answer, 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.