Home > Software design >  How to iterate json object field in react
How to iterate json object field in react

Time:11-26

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

{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

CodePudding user response:

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',
      },
    ],
  },
];
  • Related