Ghost
Ghost

Reputation: 326

how can i set object values by interval in javascript

i have a javascript problem which confusing me , i have an object with hours as keys from 09:00 to 15:00

{
 '09:00://true or false 
 '10:00:// true or false 
 '11:00: //true or false 
 '12:00'://true or false 
 '13:00'://true or false
 '14:00'://true or false
 '15:00'://true or false
}

and another array containing these objects:

[{time:'10:00', value:true}, {time:'14:00', value:false} ] 

what i want to do is to set the interval between 10:00 and 14:00 to true , before 10:00 to false and after 14:00 to false ,

{
 '09:00: false,
 '10:00: true,
 '11:00: true,
 '12:00': true, 
 '13:00': true,
 '14:00': false,
 '15:00': false 

 }

if the array contains these values :

[{time:'10:00', value:true}, {time:'12:00', value:false}, {time:'14:00', 
  value:true};{time:'15:00',value:false}] 

the expected result is:

{
 '09:00: false ,
 '10:00: true ,
 '11:00:true ,
 '12:00': false ,
 '13:00': false,
 '14:00':true, 
 '15:00':false

}

so every time the value of a key changes the values of all keys after it change to its value until it changes again , this is really confusing me i would appreciate any help

Upvotes: 0

Views: 120

Answers (1)

Mister Jojo
Mister Jojo

Reputation: 22320

you can do that

const data1 = [{time:'10:00', value:true}, {time:'14:00', value:false} ] 
   ,  data2 = [{time:'10:00', value:true}, {time:'12:00', value:false}, {time:'14:00',  value:true}, {time:'15:00',value:false}] 
   ;
   ;
function foo ( arrObj )
  {
  let res = {}
    , val = false
    , inf = arrObj.reduce((r,{time,value})=>{ r[time]=value; return r },{})
    ;
  for(let h=9; h<16; h++)
    {
    let key  = (h<10 ? `0${h}`: h) + ':00'
    res[key] = val = inf.hasOwnProperty(key) ? inf[key] : val
    }
  return res
  }

console.log( foo(data1) )
console.log( foo(data2) )
.as-console-wrapper {max-height: 100%!important;top:0}

Upvotes: 1

Related Questions