[英]Javascript array filter by checking multiple conditions
我有一個數組:
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
功能and
條件,如獲取記錄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;
});
var arr = [ { "id":3, "status": 1, "first_name":"Laila", "last_name":"McCaine", "gender":"female", "populations":[{"population_name":"Heart failure"}, {"population_name":"AMI"}], "score": 55.0 }, { "id":5, "status": 1, "first_name":"Riva", "last_name":"Rontgen", "gender":"female", "populations":[{"population_name":"Pnumonia"}], "score": 85.0 }, { "id":8, "status": 0, "first_name":"Emily", "last_name":"Rosewood", "gender":"female", "populations":[], "score": 25.0 } ]; function filterRecords( arr ){ return arr.filter(function( record ){ return record.score > 40 && record.status && (record.populations.filter(function( population ){ return population.population_name == 'Heart failure'; })).length; }); } console.log( filterRecords( arr ) );
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.