我有这个js对象数组。如何基于时间键在jsx中输出此内容?就像下面的示例一样。
[
{
articleName: "Burger",
time: "11/8/2018, 2:43:30 PM"
},
{
articleName: "Cheese",
time: "11/8/2018, 2:43:30 PM"
},
{
articleName: "Burger",
time: "11/8/2018, 2:44:30 PM"
},
{
articleName: "Cheese",
time: "11/8/2018, 2:44:30 PM"
},
{
articleName: "Burger",
time: "11/8/2018, 2:45:30 PM"
},
{
articleName: "Cheese",
time: "11/8/2018, 2:45:30 PM"
}
]
基于时间:
from 2:43:30 PM
<View>
<Text>Burger</Text>
<Text>Cheese</Text>
</View>
from 2:44:30 PM
<View>
<Text>Burger</Text>
<Text>Cheese</Text>
</View>
from 2:45:30 PM
<View>
<Text>Burger</Text>
<Text>Cheese</Text>
</View>
答案 0 :(得分:1)
一种解决方案是根据时间将数组归为一组,然后将其映射到JSX中。假设您的数组称为data
:
const dataByTime = data.reduce((acc, el) => {
if (Array.isArray(acc[el.time])) {
acc[el.time].push(el.articleName)
} else {
acc[el.time] = [el.articleName]
}
return acc
}, {})
dataByTime
的格式现在为{ [date time]: ['burger', 'cheese'], ... }
所以您可以像这样将其映射到JSX:
Object.keys(dataByTime).map((time) => (
<div>
{time}
<View>
{
dataByTime[time].map(food => (
<Text>{food}</Text>
))
}
</View>
</div>
))
您可以跳过JSX中的地图,也可以在原始的reducer中进行处理(而不是按el.articleName
,而可以按<Text>{el.articleName}</Text>
)。