Skip to content
Advertisement

Calling json postData properly

Hello stackoverflow members. So I wanna call this action nested array in json to Action Component but I dont know how. If I could get some help that would be highly appriciated

import React from 'react'
import data from "../data.json";
function Action() {
    return (
        <div>
         {data.map((postData) => {
        console.log(postData);
        return(
            <div key={postData.id}>
              <h1 >{postData.action.name}</h1>
            </div>    
        )})}
        </div>
    )
}

export default Action
[
 {
    "action":[{
    "id":"0",
    "image": "src=fsdf",
    "price" : "60$",
    "name" :"cs" 
    },
{
    "id":"1",
    "image": "src=fsdf",
    "price" : "6$",
    "name" :"whatever" 
}],

   "adventure":[{
        "id":"10",
        "image": "src=fsdf",
        "price" : "60$",
        "name" :"Cs" 
        }]
}
]

Advertisement

Answer

You could change your code to something like this:

import data from "../data.json";
//...

export default function App() {
  return (
    <div className="App">
      <div>
        {data[0].action.map((postData) => {
          return (
            <div key={postData.id}>
              <h1>{postData.name}</h1>
            </div>
          );
        })}
      </div>
    </div>
  );
}

data is an array with one object with two properties: action and adventure that are arrays.


As prasanth points out given your current data you could also remove the outer most array and make data a single object.

Then you can just map over data.action.


sandbox

Advertisement