# 用勾選方塊來篩選資料 ## 資料形式 - 陣列物件集合 ```jsonld "resources": [ { "id": 1, "topics": ["HTML/CSS"], "title": "W3School CSS Tutorial", "type": "第三方技術網站", "level": "初階", "price": "免費", "lang": ["簡體中文", "英文", "多語系"], "averageScore": 0 }, { "id": 2, "topics": ["HTML/CSS"], "title": "六角學院 - 使用 HTML、CSS 開發一個網站", "type": "線上課程", "level": "初階", "price": "付費", "lang": ["繁體中文"], "averageScore": 0 }, ] ``` --- [TOC] --- ## 過濾篩選類別 ### DOM - 利用 `[name=type]:checked` 取出有被勾選的元素 ```javascript const typeCheckedList = [...document.querySelectorAll('[name=type]:checked')]; ``` - 可使用 `forEach()` 印出來觀察 ```javascript typeCheckedList.forEach((item) => { console.log(item.value); }); ``` ### 把字串條件存進新的陣列 ```javascript const typeWords = typeCheckedList.map((item) => { // console.log(item.value); return item.value; }); console.log('typeWords:::', typeWords); ``` - 此時,陣列的內容印出來會像 ```javascript typeWords::: ["文章", "書籍"] ``` ### 陣列互相比對資料 ```javascript const afterFilter = data.filter((item, idx) => { console.log(`${idx}-"${item.type}"`); const hasIncludes = typeWords.includes(item.type); console.log('hasIncludes:::', hasIncludes); return hasIncludes; }); console.log('afterFilter:::', afterFilter); ``` - 取出原始資料的 `item.type` ```jsonld { "id": 1, ... "type": "第三方技術網站", ... }, ``` - 判斷 `"第三方技術網站"` 有沒有存在 `typeWords` 裡面 - 有則代表這筆資料符合條件 - 會把該筆資料存進新的陣列 ## 如果沒有勾選條件 - 取來的 DOM 元素 `typeCheckedList` 會是空陣列 - 會導致 `data.filter()` 過後都不符合條件,結果也是空陣列 - 所以可以先做判斷 ```javascript const hasChecked = typeCheckedList.length > 0; console.log('hasChecked:::', hasChecked); if (!hasChecked) { return data; } /* end of IF-NULL */ ``` ## END ```javascript function filterType(data) { const typeCheckedList = [...document.querySelectorAll('[name=type]:checked')]; // typeCheckedList.forEach((item) => { // console.log(item.value); // }); const hasChecked = typeCheckedList.length > 0; console.log('hasChecked:::', hasChecked); if (!hasChecked) { return data; } /* end of IF-NULL */ const typeWords = typeCheckedList.map((item) => { // console.log(item.value); return item.value; }); console.log('typeWords:::', typeWords); const afterFilter = data.filter((item, idx) => { console.log(`${idx}-"${item.type}"`); const hasIncludes = typeWords.includes(item.type); console.log('hasIncludes:::', hasIncludes); return hasIncludes; }); console.log('afterFilter:::', afterFilter); return afterFilter; } /* end of filterType(data) */ ``` <iframe src="https://stackblitz.com/edit/web-platform-7yoget?embed=1&file=play1.js&theme=dark" frameborder="0" width="100%" height="600" > </iframe>