Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading