# 期末考 Q3 結構
```javascript=
const section = Section(title, async () => {
const res = await fetchRainfall();
const filtered = res.sort((a, b) => b.rainfall - a.rainfall).slice(0, 20);
return filtered.reduce((acc, cur) => {
const { locationName, stationId, city, town, rainfall } = cur;
if (!acc[city]) acc[city] = {};
if (!acc[city][town]) acc[city][town] = {};
acc[city][town][`${locationName}_${stationId}`] = rainfall;
return acc;
}, {});
});
```
#3 `filtered` 經過排序和篩選前 20 筆的資料長這樣

有 city, locationName, rainfall, stationId, town 欄位(其實還有別的,只是先被我拿掉)
這時我們來跑一下程式
## 1. #5
```javascript=
return filtered.reduce((acc, cur) => {
...
}, {});
```
執行 `reduce`,起始值是 `{}` 空物件
## 2. #6
```javascript=
const { locationName, stationId, city, town, rainfall } = cur;
```
解構出需要的欄位(如上圖是,還不清楚的人可以再吃一下三明治,不對...是翻
filtered 是 array,第一筆資料是這樣,所以 #6 解構出來的資料就是如下對應
```json=
{
city: "臺東縣",
locationName: "蘭嶼",
rainfall: 19,
stationId: "467620",
town: "蘭嶼鄉"
}
```
## 3. #7
```javascript=
if (!acc[city]) acc[city] = {};
```
因為 `acc` 預設是 `{}`, `city` 是 `臺東縣`
而 `acc[city]` 表示是 `acc["臺東縣"]`,值是 `undefined`
經過 not 之後條件成立所以會執行
```javascript=
acc[city] = {};
```
執行完後 `acc` 是
```json=
{
"臺東縣": {}
}
```
## 4. #8
```javascript=
if (!acc[city][town]) acc[city][town] = {};
```
如同上面的,這行跑完之後 `acc` 會變成
```json=
{
"臺東縣": {
"蘭嶼鄉": {}
}
}
```
## 5. #9
``` javascript=
acc[city][town][`${locationName}_${stationId}`] = rainfall;
```
這邊做了幾件事
### i.
```javascript=
${locationName}_${stationId}
```
因為 `locationName` 有時候會有重複(雷)
我就把 `locationName` 和 `stationId` 用底線組合起來當做 property name
所以是 `蘭嶼_467620`
### ii.
把雨量 `rainfall` (值是 19)塞到 `acc["臺東縣"]["蘭嶼鄉"]["蘭嶼_467620"]` 欄位中,所以 `acc` 是
```json=
{
"臺東縣": {
"蘭嶼鄉": {
"蘭嶼_467620": 19
}
}
}
```
## 6. #10
```javascript=
return acc;
```
回傳 `acc`,經過這行之後,下一次進入迴圈時的 `acc` 起始值就會是
```json=
{
"臺東縣": {
"蘭嶼鄉": {
"蘭嶼_467620": 19
}
}
}
```
## 7. 第二次進入 reduce 迴圈
`filtered` 第二筆是
```json=
{
city: "臺東縣",
locationName: "太麻里",
rainfall: 16.5,
stationId: "C0S690",
town: "太麻里鄉"
}
```
所以經過 #6 ~ #10 處理完這筆資料後,`acc` 會是
```json=
{
"臺東縣": {
"蘭嶼鄉": {
"蘭嶼_467620": 19
},
"太麻里鄉": {
"太麻里_C0S690": 16.5
}
}
}
```
## 8.
最後依次跑完所有結果就會是如畫面所示