[英]Iterating through array of JavaScript objects and outputting it
我有這個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>
一種解決方案是根據時間將數組歸為一組,然后將其映射到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中對其進行處理(您可以按下<Text>{el.articleName}</Text>
來代替el.articleName
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.