You can make it cleaner by doing a falsy check ((!parent)
) instead of strict undefined
check,
and doing return
on console.error
so you don't need the else
block
public loadChildChild(parentName: string, childName: string, childChildName: string) {
var parent = myCollection.items.find(i => i.name === parentName)
// Do a falsy check instead of strict undefined check, then return on console.error to eleminate else block
if(!parent) return console.error(`${parentName} not found in collection`);
var child = parent.children.find(c => c.name === childName)
// Do a falsy check instead of strict undefined check, then return on console.error to eleminate else block
if(!child) return console.error(`${childName} not found in ${parentName}`);
var childChild = child.children.find(c => c.name === childChildName);
if(!childChild) return console.error(`${childChildName} not found in ${parentName}>${childName}`);
this.selectedItem = childChild;
}
Or if you don't care about console.error
if parent
is undefined
or child
is undefined
, you can do optional chaining instead
public loadChildChild(parentName: string, childName: string, childChildName: string) {
const childChild = myCollection
.items.find(i => i.name === parentName)
?.children.find(c => c.name === childName)
?.children.find(c => c.name === childChildName);
if(!childChild) return console.error(`${childChildName} not found in ${parentName}>${childName}`);
this.selectedItem = childChild;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…