使用Object.assign更新对象的内部元素

时间:2016-12-27 23:02:00

标签: javascript reactjs redux

我需要一些帮助,在我的redux reducer中使用Object.assign更新对象的内部元素。

为了更好地解释这个场景,我使用的是NBA球队。我的redux商店里有一个NBA对象。我现在只想更新特定团队的团队成员。我的NBA对象看起来像这样:

{
   teams: [
       {
          teamId: 123,
          teamName: "Los Angeles Lakers"
          teamMembers: [
             {id: "kbryant", fullName: "Kobe Bryant"},
             {id: "bingram", fullName: "Brandon Ingram"}
          ]
        },
        {
          teamId: 234,
          teamName: "Miami Heat"
          teamMembers: [
             {id: "cbosh", fullName: "Chris Bosh"},
             {id: "tjohnson", fullName: "Tyler Johnson"}
          ]
        }
   ]
}

我通过我的行动将teamId和成员传递给reducer,即action.teamId和action.members。

这是我到目前为止所做的:

Object.assign({}, state, {
   nba: Object.assign({}, state.nba, {
      teams: Object.assign({}, state.nba.teams, {
         teamId[action.teamId] // I'm stuck here...
      })
   })
})

如何更新特定团队的团队成员?我知道我几乎在那里,但可以使用一点帮助。感谢。

1 个答案:

答案 0 :(得分:1)

您可以使用动态索引属性扩展您拥有的代码,该属性旨在识别teams数组中哪个条目需要更新。 ES6语法通过将动态表达式包装在方括号中来允许对象文字中的动态属性,如下所示:{ [index]: value },其中index是变量或其他表达式。

以下是最终解决方案:

function getNewState(state, action) {
    var index = state.nba.teams.findIndex( t => t.teamId == action.teamId );
    if (index == -1) return state; // team not found
    return Object.assign({}, state, {
        nba: Object.assign({}, state.nba, {
            teams: Object.assign([], state.nba.teams, {
                [index]: Object.assign({}, state.nba.teams[index], { 
                    teamMembers: action.teamMembers 
                })
            })
        })
    });
}

var state = {
    nba: {
        teams: [{
            teamId: 123,
            teamName: "Los Angeles Lakers",
            teamMembers: [
                {id: "kbryant", fullName: "Kobe Bryant"},
                {id: "bingram", fullName: "Brandon Ingram"}
            ]
        }, {
            teamId: 234,
            teamName: "Miami Heat",
            teamMembers: [
                {id: "cbosh", fullName: "Chris Bosh"},
                {id: "tjohnson", fullName: "Tyler Johnson"}
            ]
        }]
    }
};

var action = { teamId: 123, teamMembers: [{id: "lnance", fullName: "Larry Nance"}] };
var newState = getNewState(state, action);
console.log(newState);
.as-console-wrapper { max-height: 100% !important; top: 0; }

请注意,使用像Immutable这样的库时,这种操作会变得更容易。