Reputation: 2476
So i've read a handful of SO posts and some blogs, but still can't figure out why my code isn't working.
My code:
function myFunct(d) {
if (typeof d.parent.name == "undefined") {
console.log("undefined") ;} else { console.log("defined") ;}
}
d
is an object that looks something like:
Object {
children: Object,
count: 676
}
I've tried using (!d.parent.name)
, hasOwnProperty
, ===
, and as above using typeof
. Any suggestions?
The error I recieve is TypeError: d.parent.name is undefined
UPDATE:
Ok thanks everyone for the input, and my apologies if the question was confusing. I was actually looking for d.parent.parent
but tried to simplify the question by using d.parent
. I think the problem is that d.parent
is not defined so it doesn't even get to d.parent.parent
. Sorry for not being more specific!
Upvotes: 3
Views: 1967
Reputation: 755
If you want an undefined-safe check all the way down your object tree, you can use:
if( typeof( ((d || {}).parent || {}).name ) === 'undefined') {
}
If you have the luxury of having Lodash at your disposal:
var d = {
parent: {
name: "Joe"
}
};
if ( typeof (_.get(d, "parent.name")) === 'undefined' ) {
}
Upvotes: 5
Reputation:
I believe the error is the property identifier parent
. Are you sure your object has the property? The identifier d
may be invalid because parent
doesn't exists.
Upvotes: 0
Reputation: 8926
Try to check all children with logical OR
if (typeof d == "undefined" ||
typeof d.parent == "undefined" ||
typeof d.parent.name == "undefined") {
// ...
}
Upvotes: 4
Reputation: 1346
if(typeof x === 'undefined')
Use this, it checks for type as well as value, thats what you need.
Upvotes: 1