如何从 Immutable 中的数组中删除对象?

新手上路,请多包涵

给定这样的状态:

 state = {
  things: [
    { id: 'a1', name: 'thing 1' },
    { id: 'a2', name: 'thing 2' },
  ],
};

如何创建一个新状态,其中 ID“a1”已被删除?推送新项目很容易:

 return state.set(state.get('things').push(newThing));

但我无法弄清楚如何通过其 id 属性搜索和删除对象。我试过这个:

 return state.set('tracks',
  state.get('tracks').delete(
    state.get('tracks').findIndex(x => x.get('id') === 'a2')
  )
)

但它看起来很乱,而且它只有在找到该项目时才有效,因为如果 findIndex 返回 -1 ,那是 delete 的有效值

原文由 ffxsam 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 427
2 个回答

您可以使用 Array#filter

 return state.set('things', state.get('things').filter(o => o.get('id') !== 'a1'));

原文由 Tushar 发布,翻译遵循 CC BY-SA 3.0 许可协议

当您使用 filter 时,它会迭代所有循环 -> 一种有效的方法是查找索引 => slice 并使用 splitter …

 const index = state.findIndex(data => data.id === action.id);

return [...state.slice(0, index), ...state.slice(index + 1)];

原文由 Musa 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题