Friday, November 30, 2018

javascript - for loop in react



I got this function working to get some gym classes from a .json file.



    filtrarClase(dia, hora) {
let data = this.state.data
return data.filter(clase => {
if ((clase.dia === dia) && (clase.horaclase === hora)) {

return clase.actividad
} else {
return false
}
})
.map((clase,i) => {
return (
  • {clase.actividad}

    {clase.duracion}


    {clase.hoy} {clase.sala}




  • )
    })
    }


    it's ok, just passing it some "day and hour" will return right classes.
    But then I can't find a way to loop over this function... and only be able to do this ****





      {horas[0]}

      {this.filtrarClase(1, horas[0])}

      {this.filtrarClase(2, horas[0])}

      {this.filtrarClase(3, horas[0])}

      {this.filtrarClase(4, horas[0])}

      {this.filtrarClase(5, horas[0])}

      {this.filtrarClase(6, horas[0])}





    Over and over again... 17 times..



                

      {horas[1]}

      {this.filtrarClase(1, horas[16])}

      {this.filtrarClase(2, horas[16])}

      {this.filtrarClase(3, horas[16])}

      {this.filtrarClase(4, horas[16])}

      {this.filtrarClase(5, horas[16])}

      {this.filtrarClase(6, horas[16])}





    I'm sure you can point me on the right way with a "for" or "forEach", or hope so!
    I tried this:



        actualizarLista(dia){
    const horas = ['07:30','08:15','08:30','09:30','10:30','15:00','15:15','15:30','17:30','18:00','18:15','18:30','19:00','19:30','20:00','20:30','21:30']
    for (let i=0; i return
      {this.filtrarClase(dia, horas[i])}


    }

    }

    render() {
    let dias = [1,2,3,4,5,6]
    for (let i=0; i this.actualizarLista(i)
    }
    return (



    {dias}
    .........


    I tried a for loop but only returns 1 item, so I'm doing something wrong for sure. Thanks in advance.


    Answer



    Reason is, for loop is used to iterate the array it will never return anything, if you want to return something then use map.



    Write it like this:




    actualizarLista(dia){
    const horas = ['07:30','08:15','08:30','09:30','10:30','15:00','15:15','15:30','17:30','18:00','18:15','18:30','19:00','19:30','20:00','20:30','21:30']
    return horas.map((el, i) => {
    return
      {this.filtrarClase(dia, el)}

    })
    }

    render() {
    let dias = [1,2,3,4,5,6];

    let uiItems = dias.map(i => {
    return

    {this.actualizarLista(i)}

    })

    return (

    {uiItems}


    )
    }


    Suggestion: horas array is constant so i will suggest you to define it once outside of the class.


    No comments:

    Post a Comment

    plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

    In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...