![](/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.