我有大量的 API 資料,我將其過濾到較小的數量。問題是我制作的當前系統使用 .map() 來設定該資料的順序偏好,但它會洗掉任何重復項。資料按體育聯賽過濾,因此如果同一聯賽的兩場比賽進行,兩場比賽應該進入最終陣列,但只有一場通過。有序陣列洗掉重復項。
const json = (await res.json())?.response;
const ordered = desiredOrder.map((id) => json.find(({ league }) => league?.id === id));
const filtered = [...new Set(ordered)].filter(item => item !== undefined)
這是desiredOrdered 陣列,每個聯賽都指定一個數字,然后將聯賽從好到壞排列。
var desiredOrder = [
1, 2, 3, 4, 5, 6, 7, 9, 10, 29, 30, 31, 32, 33, 34, 39, 45, 48, 140, 142, 135, 137, 78, 81, 61, 65, 66, 88, 94, 96, 253, 203, 262, 179, 185,
144, 188, 169, 40, 41, 42, 43, 235, 207, 218, 141, 136, 333, 307, 197, 62, 79, 80, 128, 130, 292, 98, 101, 103, 106, 113, 119, 283, 71, 73,
265, 239, 211, 89,
];
這是 API 輸出,因此您可以查看 id 的派生位置(這些元素超過 100 個,這是條目 0)
0:
fixture: {id: 710877, referee: 'Anthony Taylor, England', timezone: 'UTC', date: '2022-05-19T18:45:00 00:00', timestamp: 1652985900, …}
goals: {home: 3, away: 2}
league: {id: 39, name: 'Premier League', country: 'England', logo: 'https://media.api-sports.io/football/leagues/39.png', flag: 'https://media.api-sports.io/flags/gb.svg', …}
score: {halftime: {…}, fulltime: {…}, extratime: {…}, penalty: {…}}
teams: {home: {…}, away: {…}}
[[Prototype]]: Object
因此,使用上面的輸出,我需要將另一個 id 為 39 的游戲過濾到陣列中。我已經嘗試了很多事情來讓它作業,但它不起作用。
如果你想玩 WebDev --> https://footballify.net/test
Github - https://github.com/Footballify/Footballify.github.io/tree/main/test
=nn
uj5u.com熱心網友回復:
map不洗掉重復項,Set確實。
見MDN:
Set 物件是值的集合。您可以按插入順序遍歷集合的元素。Set 中的一個值只能出現一次;它在 Set 的系列中是獨一無二的。
如果要允許重復,請不要使用Set.
還有MDN
find() 方法回傳提供的陣列中滿足提供的測驗功能的第一個元素。如果沒有值滿足測驗函式,則回傳 undefined。
如果要匹配每個結果,請filter()改用。
filter() 方法創建一個新陣列,其中包含通過所提供函式實作的測驗的所有元素。
您可能想要展平分配給的陣列ordered
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478978.html
標籤:javascript jQuery json api
