2 回答

TA貢獻1859條經驗 獲得超6個贊
可以使用 Array.find()而不是使用 ,它返回數組中通過回調函數中實現的測試的所有元素,它Array.filter()
sexEnumeration
返回提供的數組中滿足所提供測試函數的第一個元素的值
這是如何完成的:
const message = (sexEnumeration.find((item) => item.key === incoming ? item.label : false )).label
以下是工作,簡潔的示例(包括@3limin4t0r的建議):
const incoming = "disi";
const sexEnumeration = [
{ key: "bebek", label: "ребенок" },
{ key: "erkek", label: "Мужчина" },
{ key: "disi", label: "женская кошка" }
];
const { label: message } = sexEnumeration.find(({ key }) => (
key == incoming
));
console.log(message);

TA貢獻1794條經驗 獲得超8個贊
一種選擇是將數組轉換為 Map 以進行快速查找。在這里,數組的使用似乎并不合適。這確實假定項屬性在項之間是唯一的。key
const sexEnumeration = [
{ key: "bebek", label: "ребенок" },
{ key: "erkek", label: "Мужчина" },
{ key: "disi", label: "женская кошка" }
];
const sexEnumerationMap = new Map(sexEnumeration.map(item => [item.key, item]));
console.log(sexEnumerationMap.get("disi").label);
console.log(sexEnumerationMap.get("bebek").label);
console.log(sexEnumerationMap.get("erkek").label);
添加回答
舉報