IWI
IWI

Reputation: 1608

Updating an object in an array if the object exists

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.

Upvotes: 2

Views: 2550

Answers (2)

JayCodist
JayCodist

Reputation: 2544

You can map through the objects in the state array, use the in operator to check if property exists on the current object, and if so, return the affected object updated with new value

const reducer = (state, action) => {
 switch(action.type){
    case "ADD_SPOUSE":
       const key = "spouse";
       if (state.some(obj => key in obj) {
           return state.map(obj => key in obj ? {[key]: action[key]} : obj)
       }
       else {
           return [...state, {[key]: action[key]}]
       }
 ...

Upvotes: 1

Sascha A.
Sascha A.

Reputation: 4616

Iterate over the array with some. Check if the key from an object is equal to the searched key. If so than update the value for this object and return with true. by this the iteration over the array is stopped.
If by this any object with the searched key is founded create a new object with a property for this key (with the value) and push it to the array.

let state = [{spouse: true}, {age: 50}, {numOfChildren: 2}];

function updateKeyValue(state, key, value) {
    let found = state.some(obj => {
        if (Object.keys(obj)[0] === key) {
            obj[key] = value;
            return true;
        }
    });
    if (!found) {
        state.push( {[key]: value});
    }
    return state;
}

console.log(updateKeyValue(state,"age",48));
console.log(updateKeyValue(state,"help",'no'));

Upvotes: 2

Related Questions