javascript - 在 React 中映射嵌套的对象数组

标签 javascript arrays reactjs ecmascript-6

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

fiddle : 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."
      }
    ]
  }
];

map 看起来像

{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 上进行映射

示例

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

关于javascript - 在 React 中映射嵌套的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51615559/

相关文章:

c - 使用动态内存分配C程序查找区间的最大值和最小值

python - 当作为参数传递给函数时获取 numpy 结构化数组列的名称

javascript - 如何在另一个屏幕访问asyncStorage的Key

Django React CSRF 问题

javascript - React - 如何访问数据集值

javascript - jquery sortable 禁用特定项目之间的拖/放

javascript - Bacon.js 累加器

arrays - 有没有办法在 TypeScript 中将多种类型的数据放入数组中?

javascript - 仅当站点没有按钮 B 时,查询选择器才选择按钮 A

javascript - 是否允许使用 client_id 进行身份验证的 Javascript Instagram 应用程序?