反应:映射对象的嵌套数组 [英] REACT: Map over nested array of objects

查看:80
本文介绍了反应:映射对象的嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试映射对象数组,其中每个数组都包含另一个嵌套的对象数组.但是,该映射不适用于嵌套数组.我如何映射嵌套数组的内容,同时将所有content保留在父对象的相同title下?

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?

提琴手: https://jsfiddle.net/69z2wepo/249197/

数据结构如下:

[
  {
    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."
      }
    ]
  }
];

地图看起来像

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

推荐答案

由于每个元素都有一个content数组,因此,您也必须在content之上map.

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

示例

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

这篇关于反应:映射对象的嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆