gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:13:17 26 4
gpt4 key购买 nike

我有一个数组:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com