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

Why is my JSON array prototype mapping not working?

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:

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 { 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.

>Solution :

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>;
})}
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