Why is my JSON array prototype mapping not working?

46 Views Asked by At

I'm trying to map the array in my JSON file but I'm doing something wrong and I can't figure out what. When I do console.log the result is "undefined". I have the feeling that the error might be in my JSON file and not necessarily in the .map function but I can't figure it out.

this is my JSON file:

{
  "homepage": {
    "servicios": {
      "subheader": "Servicios",
      "title": "Áreas de Práctica",
      "cards": [
        {
          "id": "1",
          "title": "Empresarial",
          "body": "lorem ipsum"
        },
        {
          "id": "2",
          "title": "Protección de datos personales",
          "body": "lorem ipsum"
        },
        {
          "id": "3",
          "title": "Penal",
          "body": "lorem ipsum"
        },
        {
          "id": "4",
          "title": "Laboral",
          "body": "lorem ipsum"
        },
        {
          "id": "5",
          "title": "Migratorio",
          "body": "lorem ipsum"
        }
      ]
    }
  }
}

This is my code:

import { Container, Col, Row } from "react-bootstrap";
import texts from "../../text/global.json";

function CardDeck() {
  const cards = [texts.homepage.servicios.cards];
  return (
    <>
          <Row>
            {cards.map((card) => {
              return <div>{card.title}</div>;
            })}
          </Row>
    </>
  );
}

export default CardDeck;

I use the .map function but I'm not sure I'm using it correctly. I'm guessing that probably is the way my JSON file is written. I appreciate the help.

2

There are 2 best solutions below

2
Usman Fawad On BEST ANSWER

Just do

const cards = texts.homepage.servicios.cards;

instead of

const cards = [texts.homepage.servicios.cards];

you are basically mapping inside a nested array, this way you'll have to map cards[0], so it'll be

{cards[0].map((card) => {
     return <div>{card.title}</div>;
})}
0
David On

texts.homepage.servicios.cards is already referencing an array, and you're putting it into an array:

const cards = [texts.homepage.servicios.cards];

So cards is indeed an array, and you are successfully calling .map() on it. But that array contains only one element, which itself is an array and has no title property. It basically looks like this:

[
  [
    {
      "id": "1",
      "title": "Empresarial",
      "body": "lorem ipsum"
    },
    //... etc.
  ]
]

Just reference the array itself:

const cards = texts.homepage.servicios.cards;