简体   繁体   English

如何使用索引迭代 json 文件并使用 React Native 组件进行渲染?

[英]How to iterate json file with index and render with react native component?

I have a JSON file like this:我有一个这样的 JSON 文件:

{
  "type": {
    "1": {
      "book_name": "Lorem ipsum",
    },
   "2": {
     "book_name": "Lorem ipsum",
   }
}

I need to iterate each name of this json file.我需要迭代这个 json 文件的每个名称。

In my project I import the local json file like this:在我的项目中,我像这样导入本地 json 文件:

import books from '../data/books.json';

To access each name, I can do for example:要访问每个名称,我可以这样做:

const names = books.type;
<Text>{names[1].book_name}</Text>

I'm trying to render my datas into the view with the map function but I don't understand how to use it in my case..我正在尝试使用map function将我的数据呈现到视图中,但我不知道如何在我的案例中使用它。

You can store your values in a array and you can use it in map您可以将您的值存储在一个数组中,您可以在 map 中使用它

You can do something like this:你可以这样做:

const books  = {"type":{
    "1":{
        "book_name":"Lorem ipsum",
    },
    "2":{
        "book_name":"Lorem ipsum",
    },
    "3":{
        "book_name":"Lorem ipsum",
    }
}}

    const array = [];

    Object.entries(books).map(([key, value]) => {
        Object.entries(value).map(([key, value]) => {
            Object.entries(value).map(([key, value]) => {
                array.push(value);
            })

        })
    })


  return(
    <View style={{flex:1,alignItems:"center",justifyContent:"center"}}>
  {array.map((item, key) => 
        {
            return(
            <View>
              <Text> {item} </Text>
            </View>
          )
        })}
      </View>
  );

在此处输入图像描述

Hope this helps!希望这可以帮助!

You can use Object.values(obj) but the best approach is type property been an array of objects.您可以使用Object.values(obj)但最好的方法是类型属性是一个对象数组。

{
  "type": [{  "book_name": "Lorem ipsum"}, {"book_name": "Lorem ipsum"}]
}

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

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