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

How to iterate json object field in react

There is a JSON for categories with the following structure

[
  {
    "category": "Mobiles",
    "sub": [
      {
        "name": "Apple"
      },
      {
        "name": "Samsung"
      }
    ]
  },
  {
    "category": "Televisions",
    "sub": [
      {
        "name": "Lg"
      },
      {
        "name": "Sony"
      }
    ]
  }
]

First i load data from backend to a variable called categories (On the backend side im using expressjs and pass data with res.json(JSON.parse(fs.readFileSync('categories.json')))

I want to iterate through categories sub category with

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

{categories.map(function (category, i) {
    return (
            <>
              <h6 Key={i}>{category.category}</h6> //For example: <h6>Mobiles</h6>
              <>... [logic to iterate the current category's sub categories]  ...</> //For example: <p>Apple</p> <p>Samsung</p>
            </>
    );
 })}

I tried to use a second map on category.sub like category.sub.map((s,j)=><p Key={j}>{s.name}</p>) but unfortunely i can’t get it work, and I can’t describe my problem to Google in English so it can be an easy answer and i am the big L

Any help?
Thanks

>Solution :

Try this, uncomment out the console.log to verify data if screen is white.

 return (
    <>
      {categories.map(function (category, i) {
        // console.log(category.category );
        // console.log(category.sub );
        return (
          <>
            <h6 key={i}>{category.category}</h6>
            <>
              {category.sub.map(function (sub, j) {
                // console.log(category.category + '' + sub.name);
                return <p key={j}> {sub.name}</p>;
              })}
            </>
          </>
        );
      })}
   </>
 );

Data:

let categories = [
  {
    category: 'Mobiles',
    sub: [
      {
        name: 'Apple',
      },
      {
        name: 'Samsung',
      },
    ],
  },
  {
    category: 'Televisions',
    sub: [
      {
        name: 'Lg',
      },
      {
        name: 'Sony',
      },
    ],
  },
];
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