简体   繁体   English

React Native Flatlist - 如何遍历嵌套的 object

[英]React Native Flatlist - How to loop through nested object

I have a JSON returned object from a file ./jsonData.json .我有一个 JSON 从文件 ./jsonData.json 返回./jsonData.json

Inside this file, I have this data:在这个文件中,我有这些数据:

Note: This is the whole JSON data loaded from the file.注意:这是从文件加载的整个 JSON 数据。

import QuizData from './quizData.json'

This is a new app, so QuizData is all of the following:这是一个新的应用程序,所以QuizData是以下所有内容:

[
    {
        "id": 1,
        "name": "Lesson 1",
        "topics": [
            {
                "topicID": 1,
                "topicName": "Science",
                "topicDescription": "Science quiz questions"
            },
            {
                "topicID": 2,
                "topicName": "General Knowledge",
                "topicDescription": "General Knowledge Quiz Questions"
            }
        ]
    }
]

I am trying to get the topic name for each one found and put it out as a Text.我正在尝试获取每个找到的主题名称并将其作为文本发布。

Here is my code:这是我的代码:

<FlatList
    data={QuizData}
    renderItem={({ item, index }) =>
        <View>
            <Text>{item.topics.topicName}</Text>
        </View>
    }
    keyExtractor={(item) => item.topicID.toString()}
/>

I have also tried:我也试过:

{item.topics.[index].topicName}

and

{item.topics[index][topicName]}

But I get the error:但我得到了错误:

undefined is not an object. undefined 不是 object。

I then thought perhaps its needs to be:然后我想也许它需要是:

data={QuizData.topics}

and then change the renderItem to:然后将 renderItem 更改为:

{item.topicName}

This time there is no error, but there is also no output of text to the screen.这次没有报错,但是屏幕上也没有文字的output。

You could do something like this你可以做这样的事情

import * as React from 'react';
import { Text, View, FlatList } from 'react-native';

import data from './data.json';

export default function App() {
  return (
    <FlatList
      data={data}
      renderItem={({ item, index }) => (
        <View>
          {item.topics.map((v, i) => (
            <>
              <Text>{v.topicName}</Text>
              <Text>{v.topicDescription}</Text>
            </>
          ))}
        </View>
      )}
    />
  );
}

Where data.json is a json file in the root directory with your data.其中data.json是根目录中的 json 文件,其中包含您的数据。

You need to have two maps:你需要有两张地图:

YOUR_OBJECT.map(item => Object.keys(item.topics).map(index => (
   return console.log(item.topics[index].topicName)
   )
));

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

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