简体   繁体   English

在 Redux reducer 中合并具有相同键的数组对象元素

[英]Merge array object elements with same key in Redux reducer

My reducer is as follows:我的减速机如下:

    export const favorites = (state = {
    favorites: [],
    countFavorite: [],
    }, action) => {
        switch (action.type) {
            case ActionTypes.ADD_FAVORITE:
                return { ...state, favorites: action.payload };

        case ActionTypes.COUNT_FAVORITE:
            return { ...state, countFavorite: [...state.countFavorite, action.payload] };
        default:
            return state;
    }
};

currents I get the following with the old state and the new state:电流我得到以下旧状态和新状态:

在此处输入图片说明

I would like for the new object to override the existing object with the same key in the array, any help would be very appreciated我希望新对象使用数组中的相同键覆盖现有对象,任何帮助将不胜感激

The first, you should check the key exists, then add more item:首先,您应该检查密钥是否存在,然后添加更多项目:

switch (action.type) {
    case ActionTypes.ADD_FAVORITE:
        return { ...state, favorites: action.payload };

    case ActionTypes.COUNT_FAVORITE: {
        let key = Object.keys(action.payload)[0];
        return { ...state, countFavorite: [...state.countFavorite.filter(fa => Object.keys(fa)[0] !== key), action.payload] };
    }
    default:
        return state;
}

In this case, you need to use Array.filter to only filter the object that is the same ID as the one in your action.payload out from the array, and then fill in the action.payload.在这种情况下,您需要使用Array.filter 只从数组中过滤出与您的action.payload 中ID 相同的对象,然后填写action.payload。

That should look like this.那应该是这样的。

case ActionTypes.COUNT_FAVORITE:
  return { ...state, countFavorite: [ ...state.countFavorite.filter( fav => fav.id !== action.payload.id ), action.payload] };

You can replace the ID with any unique identifier within the object.您可以将 ID 替换为对象内的任何唯一标识符。 This way you can omit out the object that you want to replace with the newer one.通过这种方式,您可以省略要替换为新对象的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM