I am trying to find the matching value
between two object values. I can iterate the array each time to get it.
But I am looking for some great simplest way ... any one help me?
here is what i look for :
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"
You can use find
method which accepts as parameter a callback function.
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));
You can use array#filter method.It will return an array but can customize the return condition
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.