Reputation: 1601
I have a JSON returned object from a file ./jsonData.json
.
Inside this file, I have this data:
Note: This is the whole JSON data loaded from the file.
import QuizData from './quizData.json'
This is a new app, so QuizData
is all of the following:
[
{
"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.
I then thought perhaps its needs to be:
data={QuizData.topics}
and then change the renderItem to:
{item.topicName}
This time there is no error, but there is also no output of text to the screen.
Upvotes: 2
Views: 3286
Reputation: 869
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.
Upvotes: 7
Reputation: 604
You need to have two maps:
YOUR_OBJECT.map(item => Object.keys(item.topics).map(index => (
return console.log(item.topics[index].topicName)
)
));
Upvotes: 0