Home > Back-end >  How to loop through json nested objects in react js
How to loop through json nested objects in react js

Time:06-10

SomeOne please help me. I am spending too long trying to display some data I wish to iterate over a nested object json response using react js and access ["1. open"] after the date. The image of json response

the json data is { "Meta Data": { "1. Information": "Weekly Prices (open, high, low, close) and Volumes", "2. Symbol": "IBM", "3. Last Refreshed": "2022-06-08", "4. Time Zone": "US/Eastern" }, "Weekly Time Series": { "2022-06-08": { "1. open": "142.9800", "2. high": "144.7300", "3. low": "140.1500", "4. close": "140.8300", "5. volume": "10659817" },

render() { console.log(this.state.users);

   return (
     // div>{this.state.users["Meta Data"]["2. Symbol"]}</div>
     <div> {Object.keys(this.state.users).map((item, i) => (
         <div key={i}> {this.state.users[item]["2022-06-08"]} 
              {Object.keys(["2022-06-08"]).map((c, i) => (
                <li key={i}>{["2022-06-08"][c]["1. open"]}</li>
              ))}
         </div>
          


       ))}


    </div> 
   );

But the error shows enter image description here

CodePudding user response:

This will work for you. Please refer to the demo too I made for you.

Stackblitz Demo: https://stackblitz.com/edit/react-ts-7zuxq4?file=index.tsx,App.tsx

 <div>
      {Object.keys(weeklyTimeSeries).map((key) => (
        <ul>
          <b>{key}</b>

          {Object.keys(weeklyTimeSeries[key]).map((ckey) => (
            <li>
              {ckey} = {weeklyTimeSeries[key][ckey]}
            </li>
          ))}
        </ul>
      ))}
 </div>

Note: I have made a general demo. So you have to map through your state variable instead of mine.

CodePudding user response:

use recursive approach to loop through the json object you will get it.

  • Related