![](/img/trans.png)
[英]Find and highlight all occurrences of a word from an array and display matching description
[英]How to display matching description of an object nested in an array?
我有一个函数,其目的是显示嵌套在数组中的特定对象的特定描述。 这个想法是,一旦函数( findSettings() )接收到一个特定的数组( systemSettings )和对象中的一些键( tab12 ),它应该运行 switch 语句并提供其匹配的描述。
换句话说,如果函数的参数是“tab12”,那么它应该返回描述,“tab12 的描述”。
我尝试使用 find 方法查找匹配的对象,并且效果很好,但如果我尝试运行 switch 语句,它会返回一个错误:“Obejct 可能未定义”。
const systemSettings = [
{key: 'tab1', value: 'Main Tab'},
{key: 'tab12', value: 'Tab 12'},
{key: 'tab13', value: 'Tab 13'},
{key: 'tab4', value: 'Tab 4'}
]
type sampObj = {
key: string;
value: string;
}
let info: string = '';
function findSetting(arr: sampObj[], settingKey: string) {
const selectedObjs = arr.find(obj => obj.key === settingKey);
switch(selectedObjs.key) {
case 'tab1':
info += 'Description for tab1';
break;
case 'tab12':
info += 'Description for tab12';
break;
case 'tab13':
info += 'Description for tab13';
break;
case 'tab4':
info += 'Description for tab4';
break;
default:
info += 'No description available'
}
}
findSetting(systemSettings, 'tab12')```
Any assistance would be highly appreciated.
Thanks.
const selectedObjs = arr.find(obj => obj.key === settingKey);
如果具有指定键的对象不在数组中,则可能返回undefined
。
您可以在执行 switch 语句之前检查对象是否未定义:
if(selectedObjs) {
switch(selectedObjs.key) {
case 'tab1':
info += 'Description for tab1';
break;
case 'tab12':
info += 'Description for tab12';
break;
case 'tab13':
info += 'Description for tab13';
break;
case 'tab4':
info += 'Description for tab4';
break;
default:
info += 'No description available'
}
}
else {
// Handle invalid settingKey case
}
我认为更简单的解决方案是使用Map 之类的东西来存储您对键的描述。 此外,TypeScript 中有一个名为Record 的方便的实用程序类型,用于类型安全。 然后你根本不需要在findSetting函数中提供你的数组
systemSettingsDescriptions: Record<string, string> = {
tab1: "Description for tab1",
tab2: "Description for tab2",
tab3: "Description for tab3"
};
systemSettings: sampObj [] = [
{ key: "tab1", value: "Main Tab" },
{ key: "tab12", value: "Tab 12" },
{ key: "tab13", value: "Tab 13" },
{ key: "tab4", value: "Tab 4" }
];
function findSetting(settingKey: string): string {
this.systemSettingsDescriptions[settingKey] || "No description available";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.