我有一个 ImmutableJS 结构,如下所示:
let state = fromJS({
// ...
foo: [{
bar: ['id1', 'id2']
},{
bar: ['id2', 'id3']
}]
});
我想映射 foo
并针对每个项目,根据要排除的另一个 id 数组过滤关联的 bar
(idsToExclude
)。
我想出了这个:
const idsToExclude = ['id3', 'id4'];
state = {
...state,
foo: state.get('foo').map((i) =>
i.set(['bar'], i.get(['bar']
.filterNot(b => idsToExclude.some(id => id === b))))
};
是否有更好、更惯用或更简洁的方式?
我问是因为这看起来很冗长。
最佳答案
我认为使用 .update
可以使它更干净一些,尽管这仍然相当长。您还可以将 .some(id => id === b)
简化为 .contains(b)
。
state = state.update('foo', foo =>
foo.map(item =>
item.update('bar',
bar => bar.filterNot(
id => idsToExclude.contains(id)))));
关于javascript - 映射一个 ImmutableJS 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47146852/