我想在两个对象值之间找到matching value
。我每次都可以迭代数组来获得它。
但我正在寻找一些最简单的方法......任何人都可以帮助我吗?
这是我要找的:
let values = [
{
"handlingFee": "0.65",
"min": "0",
"max": "50000"
},
{
"handlingFee": "0.60",
"min": "50000",
"max": "150000"
},
{
"handlingFee": "0.55",
"min": "150000",
"max": "999999999"
}
];
var findHandlingFee = function(){
return values[0].handlingFee;
}
findHandlingFee(3000); //handlingFee": "0.65
findHandlingFee(5010); //handlingFee": "0.60"
findHandlingFee(300000); //"handlingFee": "0.55"
答案 0 :(得分:3)
您可以使用find
方法接受回调功能作为参数。
let values = [ { "handlingFee": "0.65", "min": "0", "max": "50000" }, { "handlingFee": "0.60", "min": "50000", "max": "150000" }, { "handlingFee": "0.55", "min": "150000", "max": "999999999" } ];
var findHandlingFee = function(value){
return values.find(function(item){
return item.min <= value && item.max >= value;
}).handlingFee;
}
console.log(findHandlingFee(3000)); //handlingFee": "0.65
console.log(findHandlingFee(50010)); //handlingFee": "0.60"
console.log(findHandlingFee(300000));
&#13;
答案 1 :(得分:2)
您可以使用array#filter方法。它将返回一个数组,但可以自定义返回条件
let values = [{
"handlingFee": "0.65",
"min": "0",
"max": "50000"
},
{
"handlingFee": "0.60",
"min": "50000",
"max": "150000"
},
{
"handlingFee": "0.55",
"min": "150000",
"max": "999999999"
}
];
function findHandlingFee(val) {
return values.filter(function(item) {
// return that object where the val is between max and min value
return +item.min <= val && +item.max >= val;
})
}
//[0] since filter return an array,getting only object in 0 index
console.log(findHandlingFee(3000)[0].handlingFee);