0

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

3
  • What is expected if there are more elements in the array? Commented Jun 21, 2021 at 0:09
  • i added another example to the question Commented Jun 21, 2021 at 0:22
  • Is it always whole hours? Commented Jun 21, 2021 at 1:38

1 Answer 1

1

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}

Sign up to request clarification or add additional context in comments.

6 Comments

i get this error SyntaxError: Invalid or unexpected token for the ?? operator
@Ghost so, you have a version to update..., but I changed may code, And it will work on your old js version
sorry but it does not you can see the outpout in the snippest it is not what expected
@Ghost Well I forgot the boolean type, I have updated my answser
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.