在一行中写一个嵌套的过滤器

Write a nested filter in one line

假设这个

const someList = Immutable.fromJS([
  {'id': 2, foo: 'puppet'}, 
  {'id': 4, foo: 'kitten'}
]);

//Then I filter like so

const entry = someList.filter(elem => {
    return elem.get('id') === 4
});

console.log(entry);
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>

这给了我

{'id': 4, foo: 'kitten'}

如何编写过滤器函数,entry 等于 kitten,无需额外的行。

我试过了

const entry = someList.filter(elem => {
    return elem.get('id') === 4
}).get('foo');

但运气不好。

您可以找到带有 Array#find instead of using Array#filter 的项目。

使用 find,您将获得第一个找到的元素,其中谓词 returns true.

const entry = someList.find(elem => elem.get('id') === 4).get('foo');

如果您不确定要查找某个元素,您还需要一个默认对象。

const entry = (someList.find(elem => elem.get('id') === 4) || {}).get('foo');

使用解构,find 不是 filter:

const someList = [{'id':2,foo:'puppet'},{'id':4,foo:'kitten'}];
const { foo: entry } = someList.find(({ id }) => id == 4);
console.log(entry);

ImmutableJS 版本:

const someList = Immutable.fromJS([
    {'id': 2, foo: 'puppet'}, 
    {'id': 4, foo: 'kitten'}
]);

const entry = someList.find(elem => elem.get('id') === 4).get("foo");

console.log(entry);
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>

您可以在过滤后映射数组:

    
const someList = Immutable.fromJS([
  {'id': 2, foo: 'puppet'}, 
  {'id': 4, foo: 'kitten'}
]);

const entry = someList.filter(elem => {
  return elem.get('id') === 4
}).map(el => el.get('foo'));

console.log(entry);
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>