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??
hasOwnProperty is the method you're looking for
if (object.hasOwnProperty('id')) { // do stuff } 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(object.property)orif(object.hasOwnProperty('property'))if (typeof(object.id) !== 'undefined')obj.hasOwnProperty("id")id- yourobjectitself is null.if (object && object.id !== null)would solve that.object- it seems like it's ok in javascript, but other languages haveobjectas a keyword, andObjectis reserved, so I'd personally stick withobjor another alternative, if you don't have a more meaningful name.