【问题标题】:React-native map/loop multidimensional array based on index of json?基于json索引的反应原生映射/循环多维数组?
【发布时间】:2020-07-06 13:35:21
【问题描述】:

我是 React-native 新手,不知道如何映射这个 JSON:

{
    "Category Title": {
        "data": [
            {
                "id": 34,
                "name": "Blanditiis",
                "price": "10.30"
            },
            {
                "id": 25,
                "name": "Dolor omnis",
                "price": "10.37"
            }
        ]
    },
    "Second category": {
        "data": [
            {
                "id": 30,
                "name": "Cupiditate maiores consectetur ut quos",
                "price": "9.79"
            },
            {
                "id": 45,
                "name": "In facere sint quos",
                "price": "9.04"
            },
            {
                "id": 7,
                "name": "Necessitatibus",
                "price": "14.25",
            }
        ]
    },
    "Third category": {
        "data": [
            {
                "id": 39,
                "name": "Aliquam sed voluptates nihil dolore",
                "price": "5.66",
            }
        ]
    }
}

我想要的是将其映射如下:

<Text>{category_title}</Text> // foreach index of array
 {cards.map((the_date_from_the_json, index) => (
    <Card key={index} name={card.name} price={card.price} />
))}

卡片组件是一个工作组件。我唯一想不通的是如何映射这个多维数组;循环遍历该类别的简单数据,并向卡片显示数组键的标题。

【问题讨论】:

    标签: react-native ecmascript-6


    【解决方案1】:

    您可以使用 object.entries 并创建一个数组

     const arr = new Array();
      for (const [key, value] of Object.entries(data)) {
        arr.push({ title: key, data: value.data });
      }
    

    数据是上面的对象。 这将给出如下所示的数组

    [{"title":"Category Title","data":[{"id":34,"name":"Blanditiis","price":"10.30"},{"id":25,"name":"Dolor omnis","price":"10.37"}]},{"title":"Second category","data":[{"id":30,"name":"Cupiditate maiores consectetur ut quos","price":"9.79"},{"id":45,"name":"In facere sint quos","price":"9.04"},{"id":7,"name":"Necessitatibus","price":"14.25"}]},{"title":"Third category","data":[{"id":39,"name":"Aliquam sed voluptates nihil dolore","price":"5.66"}]}]
    

    您现在可以像任何其他数组一样映射它。

    arr.map(item=>{
    <Text>{item.title}</Text> 
     {item.data.map((card, index) => (
        <Card key={index} name={card.name} price={card.price} />
    ))}
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-27
      • 1970-01-01
      相关资源
      最近更新 更多