【问题标题】:How do you move an object from one array to array via feature? [closed]如何通过特征将对象从一个数组移动到另一个数组? [关闭]
【发布时间】:2019-12-18 18:56:07
【问题描述】:

我试图将一个对象从一个数组移动到另一个数组。可以将其想象为将朋友从非朋友添加/移动到朋友。我有两个数组,如下所示,我试图通过它的“id”将一个对象(即朋友)从可能移动到当前。在下面的示例中,我试图将 Parker 从可能的 id = 7 移动到当前。

 state = {
     current: [
         {
             id: 3,
             name: 'peter'
         }
     ],
     possible: [
         {
             id: 7,
        name: 'parker'
         }
     ]
 }

我在下面的尝试:

 function moveObject(state, action) {
   const { current, possible } = state;
   const movedObject = possible.splice(action.id, 1)[0];

   current.push(movedObject);

   const newState = { current, possible };
   return newState;

哪个移动了错误的对象...

【问题讨论】:

  • 您能提供移动对象的尝试吗?
  • 当然,见上面的编辑
  • 你写过possible.splice(id,1)[0] - id 来自哪里?如何选择要拼接的id?
  • ID 作为有效负载从我的应用程序发送到我的商店 - 请参阅上面的编辑(操作有效负载 - 在上面的示例中 action.id = 7)
  • 问题在我发布答案之前就关闭了,给你:function moveObject({ current, possible }, action) { current.push(possible.splice(possible.findIndex(o => o.id == action.id), 1)[0]); return { current, possible } }

标签: javascript arrays


【解决方案1】:

使用拼接时,必须使用可通过findIndex检索到的item的数字索引:

function moveObject(state, action) {
   const { current, possible } = state;
   const movedObjectIndex = possible.findIndex(u => u.id === action.id);
   const movedObject = possible.splice(movedObjectIndex, 1);

   current.push(movedObject[0]);

   const newState = { current, possible };
   return newState;
}

See splice doc on Mozilla

【讨论】:

  • splice 返回一个数组,取而代之的是possible.splice(...)[0]
  • @Klaycon:你说得对。谢谢。我已经修复了示例
猜你喜欢
  • 2017-07-11
  • 2018-02-05
  • 1970-01-01
  • 1970-01-01
  • 2018-12-20
  • 1970-01-01
  • 2015-10-31
  • 2020-07-18
  • 2023-03-25
相关资源
最近更新 更多