简体   繁体   中英

Loop through Nested Array of Objects, Rendering Different Markup

I hit a rabbit hole with a React app. I'm looping through this array of objects:

const weeklyClasses = [
  {
    id: 1,
    day: "Monday",
    classDescription: [
      { classType: "11am-12pm Jazz", teacher: "Joe" },
      { classType: "1pm-2pm Blues", teacher: "Doe" },
      { classType: "3pm-4pm Samba", teacher: "Zen" }
    ]
  },
  {
    id: 1,
    day: "Tuesday",
    classDescription: [
      { classType: "11am-12pm Rock", teacher: "Sis" },
      { classType: "1pm-2pm Tango", teacher: "Ter" },
      { classType: "3pm-4pm Salsa", teacher: "Soul" }
    ]
  },
  // ...
];

I am looping and retrieving the desired values, however, currently the classType outputs as one p

const Data = () => {
  return weeklyClasses.map((o, i) => {
    return (
      <div className="classDay" key={o.id}>
        {o.day}
        <div className="classType">
          {o.classType}
          //Right here
          <p>{o.classDescription.map(i => i.classType)}</p>
        </div>
      </div>
    );
  });
};

How can I output each classType as diff p tags?

Is it okay to be mapping on a map? (Should I, How could I) use reduce instead?

在此输入图像描述

Rather than wrapping the entire array of descriptions into a single p :

<p>{o.classDescription.map(i => i.classType)}</p>

You can wrap each class description element into a p instead:

{o.classDescription.map(i => <p>{i.classType}</p> )}
{/*                          ^^^             ^^^^  */}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM