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

JSON data print in react-js

I try to print student details in react app. its work but printing format is not correct. I store data in db.js file

const School = [
    { class: "First", student: ["sam", "anu", "rahul"], images: ["sam.jpg","anu.jpg","rahul.jpg"] },
    { class: "Second", student: ["anil", "sunil", "nikhil"], images: ["anil.jpg","sunil.jpg","nikhil.jpg"] }
  ];

And School.js

import React from "react";

function Student() {
  const { class, student, images} = data;

  return (
    <div>
      <p>{class}</p>
      {student.map((name) => (
        <div
          key={name}
          className="student"
          data-answer={name}>
          {name}-{images} /* <img src={images} alt="stud-img" /> */
        </div>
      ))}
    </div>
  );
}

export default Student;

Here data are show like

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

First
sam-sam.jpg,anu.jpg,rahul.jpg
anu-sam.jpg,anu.jpg,rahul.jpg
rahul-sam.jpg,anu.jpg,rahul.jpg

I wand result like :

First
sam-sam.jpg
anu-anu.jpg
rahul-rahul.jpg

How to print data like above, any changes in JSON data, I am new to react please help me to solve this issue, Thanks in advance

>Solution :

One way to achieve that is by using the second argument from map, the index.

But it’s important to note that this will only work if the order of the students array and images array match correctly.

function Student() {
  const { class, student, images} = data;

  return (
    <div>
      <p>{class}</p>
      {student.map((name, index) => (
        <div
          key={name}
          className="student"
          data-answer={name}>
          {name}-{images[index]} /* <img src={images} alt="stud-img" /> */
        </div>
      ))}
    </div>
  );
}
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