Javascript 从对象数组中获取值的更好方法是什么?Array.filter()替代方案?
常数输入=disi; 常量枚举=[ {键:bebek,标签:crmk_бббббббб}, {键:erkek,标签:Мжча}, {键:disi,标签:жаааааааааа ]; let message=sexEnumeration.filteritem=> item.key==传入?item.label:错误 [0]。标签 console.logsexEnumeration.filteritem=>item.key==传入?item.label:false[0]。标签 与使用Array.filter(返回sexEnumeration数组中通过回调函数中实现的测试的所有元素)不同,您可以使用 返回所提供数组中第一个 满足提供的测试功能 这是如何做到的:Javascript 从对象数组中获取值的更好方法是什么?Array.filter()替代方案?,javascript,arrays,Javascript,Arrays,常数输入=disi; 常量枚举=[ {键:bebek,标签:crmk_бббббббб}, {键:erkek,标签:Мжча}, {键:disi,标签:жаааааааааа ]; let message=sexEnumeration.filteritem=> item.key==传入?item.label:错误 [0]。标签 console.logsexEnumeration.filteritem=>item.key==传入?item.label:false[0]。标签 与使用Array.fi
const message = (sexEnumeration.find((item) =>
item.key === incoming ? item.label : false
)).label
这是一个简洁的工作示例,包括@3limin4t0r的建议:
常数输入=disi;
常量枚举=[
{键:bebek,标签:crmk_бббббббб},
{键:erkek,标签:Мжча},
{键:disi,标签:жаааааааааа
];
const{label:message}=sexEnumeration.find{key}=>
键==传入
;
console.logmessage 与使用Array.filter(返回sexEnumeration数组中通过回调函数中实现的测试的所有元素)不同,您可以使用
返回所提供数组中第一个
满足提供的测试功能
这是如何做到的:
const message = (sexEnumeration.find((item) =>
item.key === incoming ? item.label : false
)).label
这是一个简洁的工作示例,包括@3limin4t0r的建议:
常数输入=disi;
常量枚举=[
{键:bebek,标签:crmk_бббббббб},
{键:erkek,标签:Мжча},
{键:disi,标签:жаааааааааа
];
const{label:message}=sexEnumeration.find{key}=>
键==传入
;
console.logmessage 一个选项是将数组转换为用于快速查找的数组。在这里使用数组似乎并不合适。这确实假设item key属性在各个项之间是唯一的 常量枚举=[ {键:bebek,标签:crmk_бббббббб}, {键:erkek,标签:Мжча}, {键:disi,标签:жаааааааааа ]; const sexEnumerationMap=新建MapsexEnumeration.mapitem=>[item.key,item]; console.logsexEnumerationMap.getdisi.label; console.logsexEnumerationMap.getbebek.label;
console.logsexEnumerationMap.geterkek.label 一个选项是将数组转换为用于快速查找的数组。在这里使用数组似乎并不合适。这确实假设item key属性在各个项之间是唯一的 常量枚举=[ {键:bebek,标签:crmk_бббббббб}, {键:erkek,标签:Мжча}, {键:disi,标签:жаааааааааа ]; const sexEnumerationMap=新建MapsexEnumeration.mapitem=>[item.key,item]; console.logsexEnumerationMap.getdisi.label; console.logsexEnumerationMap.getbebek.label;
console.logsexEnumerationMap.geterkek.label;假设标签不能为空,也可以省略三元运算符。sexEnumeration.finditem=>item.key==传入。label@3limin4t0r啊。。抢手货谢天谢地,如果标签不能为空,还可以省略三元运算符。sexEnumeration.finditem=>item.key==传入。label@3limin4t0r啊。。抢手货谢谢