-3

In react I would like to display id and name of category. How to achieve this assuming the object below is somehow hard for me to understand.

[
    {
        "id": 1,
        "category": {
            "id": 1,
            "name": "CALZATURA",
        }
    },
    {
        "id": 2,
        "category": {
            "id": 2,
            "name": "PELLETTERIA",
        }
    }
]
dataItems.map((item, index) => {
  return (
    <div>
      <h1>{item.title}</h1>
      {category.map((c, i) => (
        <div>
          <p>{c.name}</p>
        </div>
      ))}
    </div>
  );
});
adiga
  • 34,372
  • 9
  • 61
  • 83
  • 1
    What have you tried and what didn't work as expected? Generally one would use `.map()` in a React render function to output elements from an array. The question's title implies that you already know this. So where are you stuck? – David Dec 06 '22 at 15:28
  • dataItems.map((item, index) => { return (

    {item.title}

    { category.map((c, i) =>

    {c.name}

    )}
    ) })
    – beginnerspirit Dec 06 '22 at 15:30
  • Relevant code belongs in the question, not in comments. Please update the question to include your attempt and describe specifically what isn't working as expected. (At a glance, the code in that comment should fail because you're trying to use a variable called `category` which was never defined.) – David Dec 06 '22 at 15:31

1 Answers1

2

Assuming your array is stored in a variable named const categories = [...];.

return (
  <div>
    {categories.map((category) => (
      <div>
        <span>{category.id}</span>
        <span>{category.category.name}</span>
      </div>
    )}
  </div>
)
Tarps
  • 1,928
  • 1
  • 11
  • 27