function weatherCodes(){ let codes = [{sunny:[1001]},{cloudy:[1002,1003]}] let theCode = 1003 };
如何檢查我的物件陣列以尋找其中一個是否包含我的變數 theCode
P粉5174756702023-09-10 00:39:21
使用 flat()
和 includes()
為您提供的簡單參考
function weatherCodes(){ let codes = [{sunny:[1001]},{cloudy:[1002,1003]}] let theCode = 1003 return codes.some(c => Object.values(c).flat().includes(theCode)); }; console.log(weatherCodes());
另一種選擇
function weatherCodes(){ let codes = [{sunny:[1001]},{cloudy:[1002,1003]}] let theCode = 1003 let values = codes.flatMap(c => Object.values(c)).flat() return values.includes(theCode) }; console.log(weatherCodes());