Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

367
Visualizações
Check property exist in object or not in JavaScript?

I have one problem statement.

Implement a function propertyExists(obj, path) that takes in an object and a path (string) as arguments and returns ‘False’ if the property doesn’t exist on that object or is null, else returns the value of the property.

And here is solution.

function propertyExists(obj,path) {
    // Write logic here
    let result =  obj.hasOwnProperty(path);
    if(result)
    {
     return (obj.path);       
    }
    else
    {
        return result;        
    }
}

Is this correct way of doing it?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Multiple issues: the first name of the function should represent what it is doing, Path as variable name is vague but propertyName as a variable is clear. what you should do is either:

  1. write function called, "getValue" it returns value if exist or null

    function getValue(obj,propertyName) {
            if(!obj) { // if object not exist
           return null;
            }
           return  obj[propertyName];
        }

  1. write function called, "propertyExists" should return true if exist else false.

   function propertyExists(obj,propertyName) {
        if(!obj) { // if object not exist
       return false;
        }
       return  obj.hasOwnProperty(propertyName);
    }
 

about 4 years ago · Juan Pablo Isaza Relatório

0

object->obj,propertyname->path

function propertyExist(obj, path){
           if (obj.hasOwnProperty(path)) return obj[path];
                   else return false;
                      };
about 4 years ago · Juan Pablo Isaza Relatório

0

Here, as far as I can understand, the objects could be nested also.

Let's take obj as {"a":{"b":"dadsa"}} and path as ab

Now, the the solution which you have posted will not work. Ideally, it should return dadsa, but it will return false.

Try the below code, it will work for nested objects also.

function propertyExists(obj,path) {
    // Write logic here
    var val=obj;
    for(a of path){
        val=val[a];
        if(!val)
            return false;
    }
    return val;
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda