Me gustaría obtener el valor de la matriz debajo del objeto y también proporcionar alguna comprobación de errores. Tengo el siguiente código para verificar si la clave existe y si el valor de la clave es de tipo matriz o no. en caso afirmativo, me gustaría obtener el valor de la clave. parece estar bien, pero ¿hay alguna forma mejor de obtener valor? Traté de usar const [value] = obj?.the_key pero obtuve una excepción Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)) si el valor de the_key no es una matriz o the_key no existe bajo el objeto
const obj = {'theKey': ['correct value']} const hasKey = obj['theKey'] !== undefined && Array.isArray(obj.theKey) if (!hasKey) console.log('null') const [value] = obj.theKey console.log(value)Puede usar las funciones hasOwnProperty e isArray para verificar si su objeto tiene la clave/propiedad que está buscando.
const obj = { 'theKey' : ['correct value'] }; let hasKey = obj.hasOwnProperty('theKey'); // This will return true / false if (!hasKey) { // key does not exist // error handling logic }Luego puede verificar el tipo de datos del valor si es una matriz o no
if (hasKey) { let keyVal = obj.theKey; if (Array.isArray(keyVal)) { // returns true or false // business logic with array } else { // key value is not array // error handling } }