Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if object has property javascript? [duplicate]

Tags:

javascript

I have this function:

      function ddd(object) {
        if (object.id !== null) {
            //do something...
        } 
    }

But I get this error:

Cannot read property 'id' of null

How can I check if object has property and to check the property value??

like image 733
Michael Avatar asked Sep 01 '16 15:09

Michael


People also ask

How do you check if an object has duplicate array?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

How do you check if an object has a specific property in JavaScript?

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

How do you check if an object contains a property?

The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.

How do you get a list of duplicate objects in an array of objects with JavaScript?

Duplicate objects should return like below: duplicate = [ { id: 10, name: 'someName1' }, { id: 10, name: 'someName2' } ];


1 Answers

hasOwnProperty is the method you're looking for

if (object.hasOwnProperty('id')) {
    // do stuff
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

As an alternative, you can do something like:

if (typeof object.id !== 'undefined') {
    // note that the variable is defined, but could still be 'null'
}

In this particular case, the error you're seeing suggests that object is null, not id so be wary of that scenario.

For testing awkward deeply nested properties of various things like this, I use brototype.

like image 86
deltree Avatar answered Oct 01 '22 04:10

deltree