[英]How do you move an object from one array to another array by feature?
我正在嘗試將 object 從一個陣列移動到另一個陣列。 可以將其想象為將朋友從非朋友添加/移動到朋友。 我有兩個 arrays,如下所示,我正在嘗試通過它的“id”將 object(即朋友)從可能移動到當前。 在下面的示例中,我試圖將 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。 您不需要使用Object.assign()
,它只是復制值(它只是將數組轉換為 object ,其屬性是數組索引)。
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
object,因為您正在修改舊的 state。
如果您想要快速運行的代碼,那么時間效率並不高。 但它遵循不變性。
我們只是忽略possible
的項目,並將其添加到current
。
state = { current: [ { id: 1, name: 'peter' } ], possible: [ { id: 2, name: 'parker' } ] } function addFriend(state, action) { const { current, possible } = state; return {...state, current: current.concat(possible[action.payload.index]), possible: possible.filter((_, index) => index.== action.payload,index) } } state = addFriend(state: {payload: {index. 0}}) console.log(state)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.