我正在尝试将一个对象从一个数组移动到另一个数组。可以将其视为将 friend 从非 friend 添加/移动为 friend 。我有两个数组,如下所示,我试图通过它的“id”将一个对象(即 friend )从可能的状态移动到当前状态。在下面的示例中,我尝试将 Parker 从可能状态移动到当前状态(id = 2)。
state = {
current: [
{
id: 1,
name: 'peter'
}
],
possible: [
{
id: 2,
name: 'parker'
}
]
}
function addFriend(state, action) {
const { current, possible } = state;
const addedFriend = Object.assign(
{},
state.possible.splice(action.payload.index, 1)
);
current.push(addedFriend);
const newState = { current, possible };
return newState;
}
最佳答案
由于您可以使用 splice()
删除多个元素,因此它返回一个数组。对结果进行索引以获取特定对象。您不需要使用 Object.assign()
,它只是复制值(它只是将数组转换为属性是数组索引的对象)。
var state = {
current: [
{
id: 1,
name: 'peter'
}
],
possible: [
{
id: 2,
name: 'parker'
}
]
};
function addFriend(state, action) {
const { current, possible } = state;
const addedFriend = state.possible.splice(action.payload.index, 1)[0];
current.push(addedFriend);
const newState = { current, possible };
return newState;
}
state = addFriend(state, {payload: { index: 0 }});
console.log(state);
我不确定为什么您要返回一个新的 state
对象,因为您正在就地修改旧状态。
关于javascript - 如何通过特征将对象从一个数组移动到另一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58209877/