我正在嘗試從回傳以下 json 的 api 中組織資料:
[
{
"0": "THURSDAY 25th MARCH",
"1": "",
"2": ""
},
{
"0": "Snow Patrol",
"1": "Press Conference",
"2": "16:00 - 19:35"
},
{
"0": "",
"1": "",
"2": ""
},
{
"0": "FRIDAY 26th MARCH",
"1": "",
"2": ""
},
{
"0": "Arctic Moneys",
"1": "Concert",
"2": "11:55 - 12:40"
},
{
"0": "Rush",
"1": "Practice Session",
"2": "13:05 - 13:50"
}
]
api 回傳一個只有數字作為鍵的陣列,下一個日期在空物件之后開始。
變成一個像這樣有組織的陣列:
[
{
"date": "THURSDAY 25th MARCH",
"events": [
{
"band": "Snow Patrol",
"type": "Press Conference",
"time": "16:00 - 19:35"
}
]
},
{
"date": "FRIDAY 26th MARCH",
"events": [
{
"band": "Arctic Moneys",
"type": "Concert",
"time": "11:55 - 12:40"
},
{
"band": "Rush",
"type": "Practice Session",
"time": "13:05 - 13:50"
}
]
}
]
任何幫助將非常感激!
干杯!
uj5u.com熱心網友回復:
您可以為每個物件創建一個陣列,并檢查所有 vlaues 是空字串還是最后兩個字串。
繼續或構建一個新的日期物件,然后將所有事件添加到最后一個物件。
const
data = [{ 0: "THURSDAY 25th MARCH", 1: "", 2: "" }, { 0: "Snow Patrol", 1: "Press Conference", 2: "16:00 - 19:35" }, { 0: "", 1: "", 2: "" }, { 0: "FRIDAY 26th MARCH", 1: "", 2: "" }, { 0: "Arctic Moneys", 1: "Concert", 2: "11:55 - 12:40" }, { 0: "Rush", 1: "Practice Session", 2: "13:05 - 13:50" }],
result = data.reduce((r, o) => {
const a = Object.assign([], o);
if (!a.join('')) return r;
if (!a.slice(1).join('')) {
r.push({ date: a[0], events: [] });
} else {
const [band, type, time] = a;
r[r.length - 1].events.push({ band, type, time });
}
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397331.html
標籤:javascript 数组
