昨天我給大家分享了一個在JS 中循環循環物件的實用函數,它的特點之一就是可以取得一個數組,其中包含嵌套物件的路徑目前正在循環播放。但是,在使用巢狀物件時,您可能希望在任何給定時刻檢索或驗證特定路徑中的數據,這就是當今實用函數的作用。
請隨意複製並貼上此程式碼
/** * 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"]))
實用程式碼:
/** * 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中文網其他相關文章!