简体   繁体   English

循环遍历 json 文件中的嵌套数组对象时遇到问题

[英]Having trouble looping through nested array objects in json file

I have a json file that looks similar to this:我有一个与此类似的 json 文件:

[
 {
  "January": [
      {
           "Date": "Jan 1st",
           "Event": "New Years"
      },
      {
           "Date": "Jan 17th",
           "Event": "Chinese New Year"
      }
    ],
  "February": [
      {
           "Date": "Feb 14th",
           "Event": "Valentine's Day"
      },
      {
           "Date": "Feb 29th",
           "Event": "Leap Year"
      }
    ]
 }
]

The json file is structured like this but has many more events and months. json 文件的结构是这样的,但有更多的事件和月份。

I've tried using a nested loop, and nothing is being returned in JSX.我尝试使用嵌套循环,但在 JSX 中没有返回任何内容。 I'm able to get results if I console log it, so I'm not sure if maybe I'm using the wrong functions and if I should use two map loops instead of a forEach with a map loop inside.如果我通过控制台记录它,我能够得到结果,所以我不确定我是否使用了错误的函数,以及我是否应该使用两个映射循环而不是一个内部带有map循环的forEach Here's what I've tried so far:这是我迄今为止尝试过的:

{EventsList.forEach((monthObj) => {
    const monthObjKeys = Object.keys(monthObj);
    monthObjKeys.map((monthKey) => {
        const monthArr = monthObj[monthKey];
        return (
            <div className='Events__ItemList'>
                <h1 className='Events__Month'>{monthObjKeys}</h1>
                <div className='Events__Item'>
                    <p className='Events__Date'>{monthArr.Date}</p>
                    <p className='Events__Name'>{monthArr.Name}</p>
                </div>
            </div>
        );
    });
})}

Any help/suggestions would be much appreciated任何帮助/建议将不胜感激

The main problem is .forEach() does not return anything so either you can use .map() or .flatMap() .主要问题是.forEach()不返回任何内容,因此您可以使用.map().flatMap()

I would suggest a much simpler way to resolve your issue as the following:我建议使用一种更简单的方法来解决您的问题,如下所示:

 const eventList = [{"January": [{"Date": "Jan 1st","Event": "New Years"},{"Date": "Jan 17th","Event": "Chinese New Year"}],"February": [{"Date": "Feb 14th","Event": "Valentine's Day"},{"Date": "Feb 29th","Event": "Leap Year"}]}] const events = eventList[0]; const months = Object.keys(events); const result = months.flatMap(key => events[key]); console.log(result);

Thus with the result you can .map() through as the following with your JSX :因此, result你可以.map()通过你的JSX如下:

{
   result.map(({Date, Event}, index) =>
     <div className='Events__ItemList' key={index}>
         <div className='Events__Item'>
            <p className='Events__Date'>{Date}</p>
            <p className='Events__Name'>{Event}</p>
         </div>
     </div>
   ) 
}

You need to use index attribute on every iterated elements as I suggest above.正如我上面建议的那样,您需要在每个迭代元素上使用index属性。

Read further about List and Keys in the documentation.在文档中进一步了解List 和 Keys

Using a forEach doesn't return an array of React component instances, like using .map would.使用forEach不会像使用.map那样返回 React 组件实例的数组。 I might recommend trying this (note:untested) :我可能会建议尝试这个(注意:未经测试):

{EventsList.flatMap((monthObj) => {
    const monthObjKeys = Object.keys(monthObj);
    return monthObjKeys.map((monthKey) => {
        const monthArr = monthObj[monthKey];
        return (
            <div className='Events__ItemList'>
                <h1 className='Events__Month'>{monthObjKeys}</h1>
                <div className='Events__Item'>
                    <p className='Events__Date'>{monthArr.Date}</p>
                    <p className='Events__Name'>{monthArr.Name}</p>
                </div>
            </div>
        );
    });
})}

So two changes mainly: I used flatMap at the top, since each element of this array is itself returning an array, and I RETURNED the result of the .map() call you had.所以主要有两个变化:我在顶部使用了flatMap ,因为这个数组的每个元素本身都返回一个数组,我返回了.map()调用的结果。

If I had used .map at the top instead of .flatMap , it would have been an array of arrays of Components, and I don't think React accepts that -- it wants an array of Components - just 1 layer.如果我在顶部使用.map而不是.flatMap ,它将是一个组件数组的数组,我认为 React 不会接受——它需要一个组件数组——只有 1 层。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM