larry_82
larry_82

Reputation: 339

Sort keys into a map in react

I'm having problems when i try to order keys from a state inside mi map function in react..

the original response is:

monday : {1200: {…}, 1500: {…}, 1800: {…}, 2000: {…}, 2200: {…}, 0000: {…}, 0100: {…}, 0500: {…}, 0600: {…}, 0900: {…}}

and i need to order like this:

monday : { 0000:{..} ,0100:{..}, 0500:{..} ,0600:{..} ,0900:{..}, 1200:{..}, 1500:{..}, 1800:{..}, 2000:{..}, 2200:{..} }

all this data i already have into this.state.grid, and this object has all the day of the week. so in my render i use the key like an index, but i cant sort into the map.. i try to set a new state only whit the keys and make a map inside my map, but does not work and i don 't want to have seven state only for this.. any suggestion? Thanks!

{
  _.map(this.state.grid.monday, (element , hs) => {

  return ( 
      <tr className='grid-info' key={hs}> 
         <td colSpan='2'><p className="hs">{hs} </p></td> 
         <td colSpan='3'><p className="title">{element.program}</p></td>
      </tr>
    )
  })
}  

Upvotes: 0

Views: 3048

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138247

You should turn your object into an array, that can then easily be sorted and mapped:

 Object.entries(this.state.grid.monday)
   .sort(([a], [b]) => a - b)
   .map(([hs, element]) =>  ( 
     <tr className='grid-info' key={hs}> 
         <td colSpan='2'><p className="hs">{hs} </p></td> 
         <td colSpan='3'><p className="title">{element.program}</p></td>
     </tr>
  ));

Upvotes: 1

Related Questions