假设
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');
但是没有运气。
答案 0 :(得分:2)
您可以使用Array#find
而不是Array#filter
找到该项目。
使用find
,您将获得第一个找到的谓词在其上返回true
的元素。
const entry = someList.find(elem => elem.get('id') === 4).get('foo');
如果不确定要查找元素,则还需要一个默认对象。
const entry = (someList.find(elem => elem.get('id') === 4) || {}).get('foo');
答案 1 :(得分:1)
使用解构,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>
答案 2 :(得分:0)
您可以在过滤器后映射数组:
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>