Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

enter image description here

like image 897
Null isTrue Avatar asked Jan 18 '26 12:01

Null isTrue


1 Answers

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> )}
{/*                          ^^^             ^^^^  */}
like image 142
nem035 Avatar answered Jan 20 '26 04:01

nem035



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!