我在我的对象数组列表中使用了 javascript array.find。仅当与该属性可用时相比,我才想获得该对象的另一个属性。与 t 相比,我得到的值为 'Value1' 与 t1 相比,我得到了未定义的值。我想检查“未定义”并仅在可用时获取值。const t = 'abc';const t1= 'xyz';temp = [ {key: "abc", value: "Value1}]temp.find( check => check.key === t ).value);
3 回答

拉风的咖菲猫
TA贡献1995条经验 获得超2个赞
根据您打算如何使用该值,您可能会发现作为搜索结果需要某种类型的值。这将允许您根据需要替换某些东西或什么都不替换。
const t = 'abc';
const t1= 'xyz';
temp = [ {key: "abc", value: "Value1"}]
const result = temp.find( check => check.key === t1 ) || {value:'Not Found!'};
console.log(result.value);

慕码人2483693
TA贡献1860条经验 获得超9个赞
首先,你错过了一个结束语。其次,使用some和find:
const t = 'abc';
const t1= 'xyz';
const temp = [{key: "abc", value: "Value1"}];
if (temp.some(({ key }) => key == t)) console.log(temp.find(({ key }) => key == t).value);

慕姐8265434
TA贡献1813条经验 获得超2个赞
如果您希望它抛出错误、返回未定义、返回默认值或其他内容,您可以像这样检查未定义:
x = list.find(logic)
if(x){
//carry on as normal
else{
//handle it not being found
}
添加回答
举报
0/150
提交
取消