How do I get the number of each object in a array using .map | React

Advertisements

im trying to get the number of each object in a array, then im trying to add it to my jsx code to display what one it is

I’m pulling the data from this file
tableData.js

export const data = [
  {price: 1500, isSold: false}
  {price: 1800, isSold: false}
  {price: 1650, isSold: true}
]

Table.js

import React from "react";

import {data} from "./tableData.js";

function Table() {
  return (
    <table>
      <thead>
        <tr>
          <td>Number</td>
          <td>Status</td>
        </tr>
      </thead>
      <tbody>
        {data.map((data, key) => {
          return (
            <tr>
              <td>{/* I NEED TO ADD THE NUMBER HERE */}</td>
              <td>{data.isSold ? "Sold" : "Available"}</td>
            </tr>
          )
        }
      </tbody>
    </table>
  )
}

Ive tried adding making a variable that starts at 0 and adds 1 each time it adds a row but it doesnt work (im a beginner so my strategy probably sucks)

import React from "react";

import {data} from "./tableData.js";

function Table() {
  const currentNumber = 0; // Added this

  return (
    <table>
      <thead>
        <tr>
          <td>Number</td>
          <td>Status</td>
        </tr>
      </thead>
      <tbody>
        {data.map((data, key) => {
          const setNumber = currentNumber + 1; // Added this

          return (
            <tr>
              <td>{currentNumber}</td> // Added this
              <td>{data.isSold ? "Sold" : "Available"}</td>
            </tr>
          )
        }
      </tbody>
    </table>
  )
}

>Solution :

You can get the current index of the item of your array by using the second parameter of the map function:

<tbody>
    {data.map((data, key) => {
      return (
        <tr key={key}> {/* <= Prevent the error: Each child need its own key */}
          <td>{key}</td>
          <td>{data.isSold ? "Sold" : "Available"}</td>
        </tr>
      )
    }
  </tbody>

You can learn more about the map function here: JS Map (MDN)

and there’s a link about why you should use the key prop: Understanding the key prop

Leave a ReplyCancel reply