lost9123193 lost9123193 - 1 year ago 105
React JSX Question

Replacing an object in an object array in Redux Store using Javascript/Lodash

I have an object array in a reducer that looks like this:

{id:1, name:Mark, email:mark@email.com},
{id:2, name:Paul, email:paul@gmail.com},
{id:3,name:sally, email:sally@email.com}

Below is my reducer. So far, I can add a new object to the
reducer via the following:

const INITIAL_STATE = { currentPeople:[]};

export default function(state = INITIAL_STATE, action) {
switch (action.type) {
return {...state, currentPeople: [ ...state.currentPeople, action.payload]};
return state;

But here is where I'm stuck. Can I UPDATE a person via the reducer using lodash?
If I sent an action payload that looked like this:

{id:1, name:Eric, email:Eric@email.com}

Would I be able to replace the object with the id of 1 with the new fields?

Answer Source

Yes you can absolutely update an object in an array like you want to. And you don't need to change your data structure if you don't want to. You could add a case like this to your reducer:

    return {
        currentPeople: state.currentPeople.map(person => {
            if (person.id === action.payload.id) {
               return action.payload;

            return person;

This can be be shortened as well, using implicit returns and a ternary:

    return {
        currentPeople: state.currentPeople.map(person => (person.id === action.payload.id) ? action.payload : person),

Mihir's idea about mapping your data to an object with normalizr is certainly a possibility and technically it'd be faster to update the user with the reference instead of doing the loop (after initial mapping was done). But if you want to keep your data structure, this approach will work.

Also, mapping like this is just one of many ways to update the object, and requires browser support for Array.prototype.map(). You could use lodash indexOf() to find the index of the user you want (this is nice because it breaks the loop when it succeeds instead of just continuing as the .map would do), once you have the index you could overwrite the object directly using it's index. Make sure you don't mutate the redux state though, you'll need to be working on a clone if you want to assign like this: clonedArray[foundIndex] = action.payload;.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download