Using pure javascript -- no third party / lodash etc.
Given a user looking for the existence of a deep nested node, is there a cleaner way to ensure each parent node exists so as to not return undefined?
Keeping it simple, check that a nested prop has length before performing an action.
The problem is, especially when passing props, at any given node, you could end up with undefined
.
Is there a way to avoid checking that each node exists like this:
if( !!Grandparent && !!Grandparent.Parent && !!Grandparent.Parent.child && !!Grandparent.Parent.child.prop3.length){
// do something
}
Something more like this:
(which I know is not correct as any node being undefined
hoses the process).
if(!!Grandparent.Parent.child.prop3.length) {
// do something
}
// OR
if(typeof Grandparent.Parent.child.prop3.length !== "undefined"){
// do something
}
EX:
Grandparent: {
Parent: {
child: {
prop1: 'alpha',
prop2: 'beta',
prop3: [
item: {
name: 'first',
type: 'string'
},
item: {
name: 'second',
type: 'number'
}
]
}
}
}