Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to map over array of objects which each array contains another nested array of objects. However, the map does not work on the nested array. How do i map over the contents of the nested array while keeping all the content under the same title of the parent object?

Fiddle: https://jsfiddle.net/69z2wepo/249197/

The data structure looks like:

[
  {
    title: "title1",
    content: [
      {
        imageUrl: "http://placehold.it/300x300",
        title: "Campaigns",
        description:
          "Short description explaining the use of this design in a single sentence."
      },
      {
        imageUrl: "http://placehold.it/300x300",
        title: "Events",
        description:
          "Short description explaining the use of this design in a single sentence."
      },
      {
        imageUrl: "http://placehold.it/300x300",
        title: "General",
        description:
          "Short description explaining the use of this design in a single sentence."
      }
    ]
  },
  {
    title: "title2",
    content: [
      {
        imageUrl: "http://placehold.it/300x300",
        title: "Video Template A",
        description:
          "Short description explaining the use of this design in a single sentence."
      },
      {
        imageUrl: "http://placehold.it/300x300",
        title: "Video Template A",
        description:
          "Short description explaining the use of this design in a single sentence."
      }
    ]
  }
];

The map looks like

{dataItems.map((item, index) => {
  return (
    <h1>{item.title}</h1>
    // for each item, loop over the content array objects
    <img src={item.content.imageUrl} />
    <h3>{item.content.title}</h3>
    <h3>{item.content.description}</h3>
    <hr />
  );
})}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
119 views
Welcome To Ask or Share your Answers For Others

1 Answer

Since each element has a content array, you must map over content as well.

Example

{dataItems.map((item, index) => (
  <div key={index}>
    <h1>{item.title}</h1>
    {item.content.map((c, i) => (
      <div key={i}>
        <img src={c.imageUrl} />
        <h3>{c.title}</h3>
        <h3>{c.description}</h3>
        <hr />
      </div>
    ))}
  </div>
))}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...