通过检查多个条件来过滤Javascript数组

时间:2016-04-27 12:10:42

标签: javascript arrays

我有一个数组:

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如果其值为'则不应用ngOnInit(){ this.getDecisionsGeo(); this.initializeMap(); }

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:9)

这样的事情:

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;
});

答案 1 :(得分:0)

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>