'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?



Solution 1:[1]

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);
    }
 

Solution 2:[2]

object->obj,propertyname->path

function propertyExist(obj, path){
           if (obj.hasOwnProperty(path)) return obj[path];
                   else return false;
                      };

Solution 3:[3]

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;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ankit singh
Solution 3