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
Answers
texts.homepage.servicios.cards
is already referencing an array, and you’re putting it into an array: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 notitle
property. It basically looks like this:Just reference the array itself:
Just do
instead of
you are basically mapping inside a nested array, this way you’ll have to map cards[0], so it’ll be