Home > Software engineering >  JSON data print in react-js
JSON data print in react-js

Time:06-21

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

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

CodePudding user response:

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>
  );
}

  • Related