MMTTMM
2021-06-14 17:02:27
我在我的對象數組列表中使用了 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
提交
取消