Tengo una declaración de problema.
Implemente una función propertyExists (obj, ruta) que tome un objeto y una ruta (cadena) como argumentos y devuelva 'Falso' si la propiedad no existe en ese objeto o es nula; de lo contrario, devuelve el valor de la propiedad.
Y aquí está la solución.
function propertyExists(obj,path) { // Write logic here let result = obj.hasOwnProperty(path); if(result) { return (obj.path); } else { return result; } }¿Es esta la forma correcta de hacerlo?
Múltiples problemas: el primer nombre de la función debe representar lo que está haciendo, Path como nombre de variable es vago pero propertyName como variable es claro. lo que debes hacer es:
function getValue(obj,propertyName) { if(!obj) { // if object not exist return null; } return obj[propertyName]; } function propertyExists(obj,propertyName) { if(!obj) { // if object not exist return false; } return obj.hasOwnProperty(propertyName); }objeto->obj, nombre de propiedad->ruta
function propertyExist(obj, path){ if (obj.hasOwnProperty(path)) return obj[path]; else return false; };Aquí, por lo que puedo entender, los objetos también podrían anidarse.
Tomemos obj como {"a":{"b":"dadsa"}} y ruta como ab
Ahora, la solución que ha publicado no funcionará. Idealmente, debería devolver dadsa, pero devolverá false.
Pruebe el siguiente código, también funcionará para objetos anidados.
function propertyExists(obj,path) { // Write logic here var val=obj; for(a of path){ val=val[a]; if(!val) return false; } return val; }