Antoine
Antoine

Reputation: 560

React : render over an associative array

I've got an associative array like this:

const data = []
data["01/01/2021"] = [1, 2, 3]
data["01/02/2021"] = [4, 5, 6]
data["01/03/2021"] = [7, 8, 9]

I've tried something like this :

return(
  {data.map(d => <tr>{d // some stuff here to access the correct item, it's typed}</tr>}
)

But I can't do that on an a associative array I think. I've been thinking should I use a Map() instead, because it's key / value collection, I only need the key to be sorted in the correct way, I think I can do that even on a Map() ?

Thank you for your messages, I'm on this for a while now...

Upvotes: 0

Views: 1234

Answers (1)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

JavaScript doesn't support associative arrays. See https://stackoverflow.com/a/37516003/3903374

It's best if you declare data as an object to avoid confusion when maintaining the program:

const data = {};

You can iterate over the data object's keys.

Note that an object's keys are not guaranteed to be in any order, even if you specify then in array syntax like you've done. So you'll need to sort them if you want them ordered by date.

This puts all the dates with their data on separate rows, sorted by date:

Object.keys(data)
  .sort((date1, date2) => new Date(date1) - new Date(date2))
  .map(date => (
     <tr>
       <td>{date}</td>
       {data[date].map(d => <td>{d}</td>)}
     </tr>
   ))

Based on your comment that each data point should be on a separate row, this should do it:

Object.keys(data)
  .sort((date1, date2) => new Date(date1) - new Date(date2))
  .map(date => (
     <>
       <tr><td>{date}</td></tr>
       {data[date].map(d => <tr><td>{d}</td></tr>)}
     </>
   ))

Upvotes: 1

Related Questions