React-native map/loop multidimensional array based on index of json?

懵懂的女人 提交于 2021-01-29 08:53:00

问题


I'm new to React-native and cannot figure out how to map this 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",
            }
        ]
    }
}

What I want is to map this as following:

<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} />
))}

The Card component is a working component. The only thing I can't figure out is how to map this multidimensional array; looping through easy data of the category with showing the Card an a Title of the Key of the Array.


回答1:


You can use the object.entries and create an array

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

The data is the object above. Which will give the array like below

[{"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"}]}]

You can map it like any other array now.

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


来源:https://stackoverflow.com/questions/62757272/react-native-map-loop-multidimensional-array-based-on-index-of-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!