Home > database >  Mapping through multiple nested objects in JSON
Mapping through multiple nested objects in JSON

Time:12-15

I am working on a simple project in React and being new in React I was having trouble in mapping through the given json file to send required objects to different components.

This is what JSON file I have been given(through api)

{
   "trees":{
      "name":"a",
      "age":"9",
      "height":"10",
      "location":"park"
   },
   "cars":{
      "name":"b",
      "age":"30",
      "height":"10",
      "location":"park"
   },
   "bikes":{
      "name":"c",
      "age":"110",
      "height":"10",
      "location":"park"
   },.........................

This is the json which I am fetching in App.js. My idea is to send this completely to another component(Data.js) then from data.js to another component which will have trees, cars, bikes . I am not able to map through this json file at any level even after doing const d = [jsonfile] even after this I get undefined while mapping.

App.js

const[Data,setData] = useState([]);

  useEffect(()=>{
    fetch('API-HERE').then((result)=>{result.json().then((resp)=>{
      setData(resp); 
    })})
  },[])

return (
    <div className="App">
      <DataFetched data={Data} />
    </div>
  );

After this I am unable to map in DataFetched.js to send it to another child only trees cars bikes seprately so that their attributes can be read.

CodePudding user response:

Use Object.entries iterate over the JSON properties.

You can try like this.

import React from "react";

const DataFetched = ({ data }) => {
    if (!data) {
        return null;
    }
    return Object.entries(data).map(
        ([key, { name, age, height, location }]) => {
            return (
                <div key={key}> 
                    <div>{name}</div>
                    <div>{age}</div>
                    <div>{height}</div>
                    <div>{location}</div>
                </div>
            );
        }
    );
};

export default DataFetched;

Or you can receive the data from another child component.

import React from "react";

const MyChildComponent = ({ data: { name, age, height, location } }) => {
    return (
        <div>
            <div>{name}</div>
            <div>{age}</div>
            <div>{height}</div>
            <div>{location}</div>
        </div>
    );
};

const DataFetched = ({ data }) => {
    if (!data) {
        return null;
    }
    return Object.entries(data).map(
        ([key, value]) => {
            return (
                <MyChildComponent data={value}/>
            );
        }
    );
};

export default DataFetched;
  • Related