ffxsam ffxsam - 7 months ago 31
Javascript Question

How to remove an object from an array in Immutable?

Given a state like this:

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


How can I create a new state where ID "a1" is removed? It's easy enough to push new items:

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


But I can't figure out how to search for and remove an object by its
id
property. I tried this:

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


But it seems messy, plus it only works if the item is found, because if
findIndex
returns
-1
, that's a valid value for
delete
.

Answer

You can use Array#filter.

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