基于JSON索引的React-Native Map/Loop多维数组? [英] React-native map/loop multidimensional array based on index of json?
本文介绍了基于JSON索引的React-Native Map/Loop多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是React-native的新手,无法弄清楚如何映射此JSON:
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.
推荐答案
您可以使用object.entries并创建一个数组
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} />
))}
})
这篇关于基于JSON索引的React-Native Map/Loop多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文