ffxsam ffxsam - 1 year ago 94
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
property. I tried this:

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

But it seems messy, plus it only works if the item is found, because if
, that's a valid value for

Answer Source

You can use Array#filter.

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