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??
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.
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
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.
Duplicate objects should return like below: duplicate = [ { id: 10, name: 'someName1' }, { id: 10, name: 'someName2' } ];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With