当我需要同时过滤多个事物时,如何调用一次filter? [英] How can I call filter once when I need to filter multiple things at the same time?
本文介绍了当我需要同时过滤多个事物时,如何调用一次filter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用lodash进行一些过滤.
I am using lodash to perform some filtering.
我具有以下功能:
filterByCardinalPoint = (key, value) => {
const { passengersData } = this.props;
console.log('passengersData', passengersData);
return filter(passengersData, [key, value]);
};
callFilter = () => {
passengersGoingNorth = this.filterByCardinalPoint('cardinalpoint', 'N')
.length;
passengersGoingSouth = this.filterByCardinalPoint('cardinalpoint', 'S')
.length;
passengersGoingWest = this.filterByCardinalPoint('cardinalpoint', 'W')
.length;
passengersGoingEast = this.filterByCardinalPoint('cardinalpoint', 'E')
.length;
};
我正在render方法中调用callFilter
.此功能被调用约8次.我该如何优化它才能调用一次?
And I am calling callFilter
in the render method. This function is called around 8 times. How can I optimize it so that is call once?
推荐答案
由于您需要各个方向的人数,因此可以使用 _.property()
作为iteratee.分解结果对象以将数字分配给变量.
Since you need the amount of people going in each direction, you can use _.countBy()
with _.property()
as the iteratee. Destructure the result object to assign the numbers to the variables.
示例:
const { countBy, property } = _;
let passengersGoingNorth, passengersGoingSouth, passengersGoingWest, passengersGoingEast;
const passengersData = [{ cardinalpoint: 'N' }, { cardinalpoint: 'N' }, { cardinalpoint: 'S' }, { cardinalpoint: 'N' }, { cardinalpoint: 'E' }];
({
N: passengersGoingNorth = 0,
S: passengersGoingSouth = 0,
W: passengersGoingWest = 0,
E: passengersGoingEast = 0
} = countBy(passengersData, property('cardinalpoint')));
console.log(passengersGoingNorth, passengersGoingSouth, passengersGoingWest, passengersGoingEast); // 3, 1, 0, 1
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
这篇关于当我需要同时过滤多个事物时,如何调用一次filter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文