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'
}
]
}
}
}
CodePudding user response:
As commenters have indicated, modern JavaScript provides the optional chaining operator (?.
), which you can use like this (as long as you're not still trying to support IE):
const
grandparent = getObject(),
itemsCount = grandparent?.parent?.child?.prop3?.length,
oops = grandparent?.parent?.child?.length;
console.log(itemsCount ?? "No such property");
console.log(oops ?? "No such property");
function getObject(){
return {
parent: {
child: {
prop1: 'alpha',
prop2: 'beta',
prop3: [
{ item: { name: 'first', type: 'string' }},
{ item: { name: 'second', type: 'number' }}
]
}
}
};
}