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!
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!
- @ForceMagic I receive the same error. – As3adTintin Commented Apr 11, 2016 at 21:15
-
1
typeof Object === 'undefined'
is a valid way to use typeof – NickSlash Commented Apr 11, 2016 at 21:17 - @NickSlash sry, my bad :) – ForceMagic Commented Apr 11, 2016 at 21:18
-
@NickSlash Thanks, unfortunately I still get the same
TypeError
– As3adTintin Commented Apr 11, 2016 at 21:18 -
can you give this a try?
if (d.parent && typeof d.parent.name === 'undefined')
– NickSlash Commented Apr 11, 2016 at 21:20
4 Answers
Reset to default 5If 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' ) {
}
Try to check all children with logical OR
if (typeof d == "undefined" ||
typeof d.parent == "undefined" ||
typeof d.parent.name == "undefined") {
// ...
}
if(typeof x === 'undefined')
Use this, it checks for type as well as value, thats what you need.
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.