昨天我给大家分享了一个在 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中文网其他相关文章!