使用 immutability-helper 合并数组

3

I get the following error from the code below:
Error: update(): $merge expects a target of type 'object'; got undefined

I am trying to merge 2 arrays while only updating certain values in the items in the original array. For example, I want to update the status and updated properties but not the members array property.

I think that the issue may be with the use of index in the update method but that is just a guess. Any ideas? If there is a better approach, I would like to know it.

const oldProjects = [
    {id: 1, members:[{name: 'Al'},{name: 'Joe'}], status: 'new', updated: '2017-05-19 12:00:00'},
];

const newProjects = [
    {id: 1, members:[], status: 'in-progress', updated: '2017-05-19 14:05:00'},
    {id: 2, members:[], status: 'new', updated: '2017-05-19 14:10:00'},
    {id: 3, members:[], status: 'completed', updated: '2017-05-19 14:15:00'},
];

let newState = oldProjects;

newProjects.forEach(np => {
    const index = oldProjects.findIndex(op => op.id === np.id);
    if (index === -1) {
        newState = update(newState, {$push: np});
    } else {
        newState = update(newState, {
            index: {$merge: { status: np.status, updated: np.updated }}
        });
    }
});

1个回答

5
当使用动态键时,您需要在[]中指定它。因此,请将您的index包装在[]中,以访问索引等于index的对象,否则它只会在newState中寻找键index
尝试一下:
newProjects.forEach(np => {
    const index = oldProjects.findIndex(op => op.id === np.id);
    if (index === -1) {
        newState = update(newState, {$push: np});
    } else {
        newState = update(newState, {
            [index]: {$merge: { status: np.status, updated: np.updated }}
        });
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接