gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:15:05 25 4
gpt4 key购买 nike

给定这样的状态:

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

如何创建删除 ID“a1”的新状态?推送新项目很容易:

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

但我不知道如何通过 id 搜索和删除对象属性(property)。我试过这个:

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

但这看起来很困惑,而且只有找到该项目才有效,因为如果 findIndex返回-1 ,这是 delete 的有效值.

最佳答案

您可以使用Array#filter .

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

关于javascript - 如何从 Immutable 数组中删除对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36761056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com