我從 api 得到以下回應。下面是示例回應不是真實的每個物件都 createdDate ,我必須按天分組值,例如在 2022-09-20(星期二)創建了 2 個 customerId,而在 2022-09-21(星期三)只有一個。
{
"data": {
"fetchOrdersAndRequest": [
{
"id": "PI786971",
"customerId": [
"C200147"
],
"createdDate": "2022-09-21T04:46:00.126Z",
}
{
"id": "PI786969",
"customerId": [
"C200146"
],
"createdDate": "2022-09-20T04:46:00.126Z",
}
{
"id": "PI786968",
"customerId": [
"C200145"
],
"createdDate": "2022-09-20T04:46:00.126Z",
}
]
}
}
我必須轉換回應,例如,星期二我有 2 個回應,所以它應該在 tue array 和 Wedensday 一個,所以只有一個并且休息 emply,但如果資料來自其他日子,它也應該在那里填寫。
{
period:'lastWeek',
data:[
{
"key":"SUN",
"value" : []
},
{
"key":"MON",
"value" : []
},
{
"key":"TUE",
"value" : [{},{}],
},
{
"key":"WED",
"value" : [{}],
},
{
"key":"THU",
"value" : []
},
{
"key":"FRI",
"value" : []
},
{
"key":"SAT",
"value" : []
}
]
請幫忙 。謝謝
uj5u.com熱心網友回復:
將您的日期字串轉換為一個Date物件允許您獲取一周的日期編號,使用getDay()它給出一個數字(0-6)
可以創建一個函式來根據日期編號回傳日期名稱
之后是通常的分組使用reduce
const x = { "data": { "fetchOrdersAndRequest": [{ "id": "PI786971", "customerId": [ "C200147" ], "createdDate": "2022-09-21T04:46:00.126Z", }, { "id": "PI786969", "customerId": [ "C200146" ], "createdDate": "2022-09-20T04:46:00.126Z",}, { "id": "PI786968", "customerId": [ "C200145" ], "createdDate": "2022-09-20T04:46:00.126Z", } ] }}
const getDayName = (day) => {
return ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][day]
}
const res = x.data.fetchOrdersAndRequest.reduce((acc,curr) => {
const {createdDate} = curr
const day = new Date(createdDate).getDay()
acc[getDayName(day)].push(curr)
return acc
},{'Sun':[], 'Mon':[], 'Tue':[], 'Wed':[], 'Thu':[], 'Fri':[], 'Sat':[]})
console.log(res)
編輯問題已更改,現在可以使用陣列索引單獨使用天數來解決
const x = { "data": { "fetchOrdersAndRequest": [{ "id": "PI786971", "customerId": [ "C200147" ], "createdDate": "2022-09-21T04:46:00.126Z", }, { "id": "PI786969", "customerId": [ "C200146" ], "createdDate": "2022-09-20T04:46:00.126Z",}, { "id": "PI786968", "customerId": [ "C200145" ], "createdDate": "2022-09-20T04:46:00.126Z", } ] }}
const accumulator = {
period: 'lastWeek',
data: [{
"key": "SUN",
"value": []
},
{
"key": "MON",
"value": []
},
{
"key": "TUE",
"value": [],
},
{
"key": "WED",
"value": [],
},
{
"key": "THU",
"value": []
},
{
"key": "FRI",
"value": []
},
{
"key": "SAT",
"value": []
}
]
}
const res = x.data.fetchOrdersAndRequest.reduce((acc,curr) => {
const {createdDate} = curr
const day = new Date(createdDate).getDay()
acc.data[day].value.push(curr)
return acc
},accumulator)
console.log(res)
uj5u.com熱心網友回復:
您可以遍歷物件,然后使用:new Date(item.createdDate).getDay()檢查日期在哪一天。
然后使用它將您的專案推送到新陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/528292.html
標籤:javascript反应式约会时间ecmascript-6
