使用immutability-helper合并数组 [英] using immutability-helper to $merge an array
问题描述
我从下面的代码中收到以下错误:
错误:update():$ merge期望目标类型为'object';不确定
我试图合并2个数组,而只更新原始数组中项目中的某些值.例如,我要更新 status 和 updated 属性,而不是 members 数组属性.
我认为问题可能出在更新方法中使用 index ,但这只是一个猜测.有任何想法吗?如果有更好的方法,我想知道.
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 }}
});
}
});
推荐答案
使用动态键时,需要在[]
中指定它.因此,将index
包裹在[]
中,以访问索引等于index
的对象,否则它将在newState中寻找键index
While using a dynamic key, you need to specify it within []
. So wrap you index
within []
to get access to object at index equal to index
otherwise it will just be looking for key index
in newState
尝试
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 }}
});
}
});
这篇关于使用immutability-helper合并数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!