Home > Software engineering >  How to compare and get object value in javascript object
How to compare and get object value in javascript object

Time:04-13

I have this JS object ( data will be diffrent , it's just for example )

{10: 0, 
    30: 2.5, 
    365: 15, 
    730: 25, 
    1095: 35}

Key is Days and value is percentage. Now if input is between 0 to 10 days then percentage will be 0, if between 11 to 30 days then percentage will be 2.5 if between 31 to 365 days then percentage will be 15 if 1100 days then 35

here is my code

days - > input 
obj_data - object 
    jQuery.each(obj_data, function(key, val) {
        if( days <= key ){
            console.log(val);
            return false;
        }
    });
    return true

here how to get value if days are greater than to 1095

CodePudding user response:

By adding a value that is higher than anything else for what's possible, you have a value you can check for. If that value is returned, get the "largest"/"last" value from the provided values.

In the example below I use concat to add the largest safe integer to the array, so the compare function keeps running.

If that value is returned, we know we didn't have a match, so we get the last value from the provided object.

let data = {10: 0, 
    30: 2.5, 
    365: 15, 
    730: 25, 
    1095: 35}
let days = [1,11,31,366,731,1096]
function find(day, obj) 
{
  let keys = Object.keys(obj);
  result = keys.concat(Number.MAX_SAFE_INTEGER).filter(key => {
     return day <= key;
  }).shift();
  
  if(result === Number.MAX_SAFE_INTEGER) {
     result = keys.pop();
  }
  return obj[result];
}
days.forEach(day => console.log(day, " gets value:",find(day, data)))

  • Related