Search code examples
javascriptreactjshandlebars.jsmarionetteramda.js

Mapping Object React -> Issue with Keys


Converting a handlebars/ marionette project into React.

Need to map an array of two objects:

[{COAL: 462, GAS: 400, MIXED: 230, OIL: 288, TOTAL: 1380}, {COAL: 0, GAS: 0, MIXED: 0, OIL: 0, TOTAL: 0}]

This is how I'm currently doing that:

<tr className="Total">
    <td className="tableBoldBorder  hide">Total</td>
    {props.totals.map(totals =>
        R.values(totals).map(totals => (
            <td className="{{@key}}Column">{formatNumberValues(totals)}</td>
        ))
        )}
</tr>

All well and good. Observe @key though, that is still a handlebars function. Essentially, I want the classname to coincide with the column being rendered ie. COALColumn -> 462, GASColumn -> 400 etc.

The issue is, I have lost the keys during the mapping process. R.values(totals).map gives the following output:

[[462, 400, 230, 288, 1380], [0, 0, 0, 0, 0]]

Is there anyway to get access to the keys to allow for dynamic, mapped classNames?

Thanks for reading!

edit:

What I'm currently getting:

enter image description here

Result I want:

enter image description here

The className "TOTALColumn" will render a border on that specific column. Hard coding this, as I've done in the attached image, is not an option.


Solution

  • You could use Object.keys instead of Object.values to map over the keys:

    <tr className="Total">
      <td className="tableBoldBorder  hide">Total</td>
      {props.totals.map(totals =>
        Object.keys(totals).map(key => (
          <td className={`${key}Column`}>{formatNumberValues(totals[key])}</td>
        ))
      )}
    </tr>