取得並驗證嵌套物件中的路徑 - util 函數 #2
昨天我給大家分享了一個在JS 中循環循環物件的實用函數,它的特點之一就是可以取得一個數組,其中包含嵌套物件的路徑目前正在循環播放。但是,在使用巢狀物件時,您可能希望在任何給定時刻檢索或驗證特定路徑中的數據,這就是當今實用函數的作用。
- getDataFromObj(obj, path):從物件中的給定路徑擷取資料
- isValidObjPath(obj, path): 驗證物件中是否存在給定路徑
getDataFromObj(對象,路徑)
請隨意複製並貼上此程式碼
/** * Retrieves data from an object on a given path * @param {Object} obj the object to get the data from * @param {string[]} path an array of strings containing the keys of the object to look at * @returns {*} the retrieved data or a Reference Error if not found */ function getDataFromObj(obj, path){ // Validate arguments if(getType(obj) != "object"){ throw TypeError("The `obj` argument is not an object"); } if(getType(path) != "array"){ throw TypeError("The `path` argument is not an array"); } // Get the data or a ReferenceError if not found const data = (()=>{ let currentData = obj; for(let i = 0; i < path.length; i +=1 ){ if(Object.keys(currentData).includes(path[i])){ currentData = currentData[path[i]]; continue; } else{ currentData = ReferenceError("The object path is not defined"); break; } } return currentData; })(); return data; } /** * A method to detect data types more accurately * Credits: Chris Ferdinandi, https://gomakethings.com/ * @param {*} data the data to be verified * @returns {String} the data type */ function getType(data){ return Object.prototype.toString.call(data).toLowerCase().slice(8, -1) } /** * License: MIT, https://opensource.org/license/mit * Copyright (c) 2024 Rodrigo Isaias Calix */
用法:
您必須傳遞 2 個參數:
obj:要從中擷取資料的物件
path:指示要遵循的順序的陣列
如果路徑存在則傳回該值(即使該值未定義),如果路徑不存在則傳回ReferenceError對象,它不會拋出錯誤,只是傳回錯誤物件。
const products = { computers: { laptop: 20, desktop: 15, mini: 8 }, cameras: 20, externalDevices: { keyboard: { usb: 45, bluetooth: 25, other: undefined } } } // This would log 25 console.log(getDataFromObj(products, ["externalDevices", "keyboard", "bluetooth"])) // this would return a ReferenceError object (not a throw, just the error object) console.log(getDataFromObj(products, ["externalDevices", "mouse"])) // this would return `undefined` console.log(getDataFromObj(products, ["externalDevices", "keyboard", "other"]))
isValidObjPath(obj, 路徑)
實用程式碼:
/** * verify if an object has an specific path * @param {Object} obj the object to be verified * @param {string[]} path an array of strings containing the keys of the object to look at * @returns {Boolean} `true` if found, otherwise `false` */ function isValidObjPath(obj, path){ // Validate arguments if(getType(obj) != "object"){ throw TypeError("The `obj` argument is not an object"); } if(getType(path) != "array"){ throw TypeError("The `path` argument is not an array"); } // shallow copy of the object to be verified let currentData = obj; // Verify the path for(let i = 0; i < path.length; i +=1 ){ if(Object.keys(currentData).includes(path[i])){ currentData = currentData[path[i]]; continue; } else{ return false; } } return true; } /** * A method to detect data types more accurately * Credits: Chris Ferdinandi, https://gomakethings.com/ * @param {*} data the data to be verified * @returns {String} the data type */ function getType(data){ return Object.prototype.toString.call(data).toLowerCase().slice(8, -1) } /** * License: MIT, https://opensource.org/license/mit * Copyright (c) 2024 Rodrigo Isaias Calix */
用法:
您必須傳遞 2 個參數:
obj:要驗證路徑是否存在的物件
path:指示要遵循的順序的陣列
如果尋找的路徑存在,則傳回true,否則回傳false
const products = { computers: { laptop: 20, desktop: 15, mini: 8 }, cameras: 20, externalDevices: { keyboard: { usb: 45, bluetooth: 25, other: undefined } } } // This would log true console.log(isValidObjPath(products, ["externalDevices", "keyboard", "bluetooth"])) // this would log false console.log(isValidObjPath(products, ["externalDevices", "mouse"])) // this would log true console.log(isValidObjPath(products, ["externalDevices", "keyboard", "other"]))
為什麼使用數組作為路徑而不是帶有斜杠或點的字串? (例如“計算機.筆記型電腦”)
因為物件屬性名稱也可以是具有大範圍字元集的字串,其中包括點,因此,例如,「computers.laptop」:{[...]}將是一個有效的對象,一個陣列將提供更大的靈活性和準確性。
如果您覺得這有用,我將在 DEV 上分享更多類似的內容!
您也可以在 X 上找到我:https://x.com/schemetastic
記得保存以供日後使用?
以上是取得並驗證嵌套物件中的路徑 - util 函數 #2的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務
