【问题标题】:map two different arrays one within the other在另一个中映射两个不同的数组
【发布时间】:2019-05-13 17:16:42
【问题描述】:

我在 reactJS 中有两个不同的数组,想将一个映射到另一个数组中。

数组日历:

[
  {
     "week_number": 1,
     "from": "Wednesday May 1st 2019",
     "to": "Saturday May 4th 2019"
  },
  {
     "week_number": 2,
     "from": "Sunday May 5th 2019",
     "to": "Saturday May 11th 2019"
  },
  {
     "week_number": 3,
     "from": "Sunday May 12th 2019",
     "to": "Saturday May 18th 2019"
 },

]

和数组行:

[
  {
     "index": 1,
     "name": "job mzito",
     "date": "01/30/2019",
     "regno": "C027-01-1200/2016"
  },
 {
     "index": 2,
     "name": "Samwel Kamwana",
     "date": "01/30/2019",
     "regno": "C027-01-1879/2016"
  },
 {
     "index": 3,
     "name": "denis  mwaniki",
     "date": "02/03/2019",
     "regno": "C027-01-1256/2016"
  },

]

因此,对于日历数组中的每个项目,我希望将项目的属性与行数组中的所有项目一起显示。但是下面的地图函数什么也不返回。任何帮助将不胜感激。

这是我目前所拥有的:

<div className="content-section">
{calendar.map((period, index) => {
  {data.rows.map(row => 
      {
        return <p key={index}> Week: {period.week_number} Starting From: {period.from} To: {period.to}</p>
        return <p>{row.name}{row.date}{row.regno}</p>
      }
    )}                                     
})}
</div>

【问题讨论】:

  • 为什么不在返回之前合并两个数组?
  • 第二个return 语句永远不会到达。
  • @wentjun 之后我想设置一些条件。如果 row.date 存在于 period.from 和 period.to 中,则显示行。那种事

标签: javascript reactjs array-map


【解决方案1】:

您的返回语句位置不正确,您的日历数据必须在第一个地图中,而第二个地图中的行

<div className="content-section">
    {calendar.map((period, index) => {
        return (
           <React.Fragment>
              <p key={index}> Week: {period.week_number} Starting From: {period.from} To: {period.to}</p>
              {data.rows.map(row => {
                  return <p>{row.name}{row.date}{row.regno}</p>
              })}
           </React.Fragment>     
        )                         
    })}
</div>

【讨论】:

  • 这就像一个魅力。谢谢!不知道 React 片段
  • 很高兴有帮助:),React Fragments 是在 v16.2 中引入的
猜你喜欢
  • 2021-05-29
  • 1970-01-01
  • 2019-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
相关资源
最近更新 更多