我有一个数组:
var arr =
[
{
"id":3,
"first_name":"Laila",
"last_name":"McCaine",
"gender":"female",
"populations":[{"population_name":"Heart failure"}, {"population_name":"AMI"}],
"score": 55.0
},
{
"id":5,
"first_name":"Riva",
"last_name":"Rontgen",
"gender":"female",
"populations":[{"population_name":"Pnumonia"}],
"score": 85.0
},
{
"id":8,
"first_name":"Emily",
"last_name":"Rosewood",
"gender":"female",
"populations":[],
"score": 25.0
}
];
和变量:
var score='';
var population='';
var status = '';
我想在 和
条件下使用数组 filter
函数,例如
获取 score
小于 40、status
= 1 且 population_name
为“心力衰竭”的记录。
问题是,给定 3 个变量是 dynamic
并且如果其值为 '',则不应应用 filter
。
我怎样才能做到这一点?
最佳答案
像这样:
arr.filter(function(item) {
var ok = true;
if (score !== '') {
ok = item.score < score;
}
if (ok && population !== '') {
// check it
ok = item.populations.map(function() {return item.population_name;}).indexOf(population) > -1;
}
if (ok && status !== '') {
// check status
}
return ok;
});
关于通过检查多个条件的 Javascript 数组过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36889430/