Reputation: 115
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 }}
});
}
});
Upvotes: 3
Views: 3542
Reputation: 281726
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
Try
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 }}
});
}
});
Upvotes: 5