[英]Check if all the values in array of object is equal to false and return true in react
[英]react on change check if equal to array of object
我有輸入和我需要的對象數組,當我輸入它會顯示該對象。 “airplaneCompany”是我需要比較的對象屬性,只有當輸入等於“airplaneCompany”時,它才會通過過濾器方法返回它,但我需要 evrey char,它會檢查它,如果對象以"a" 它將顯示這個對象
const [txtInp, setTxtInp] = useState("");
const showFlight = users.filter((user) => {
return user.airplaneCompany == txtInp;
});
{showFlight.map((user, index) => {
const { id, airplaneCompany, passenger } = user;
return (
<div className="flightContainer" key={index}>
<div>{id}</div>
<div>{airplaneCompany}</div>
<div>{passenger}</div>
</div>
);
})}
我認為您可以使用 .filter 函數來檢查飛機公司是否從用戶輸入開始?
就像是
返回 user.airplaneCompany.indexOf(txtInp) === 0;
您可以使用@Patrick 答案,但 JavaScript 有自己的startsWith函數可以使用。
此外,請考慮使用useMemo
掛鈎包裝過濾器,以便僅在輸入更改時運行它,而不是在每次渲染時運行。
const showFlight = useMemo(() => {
return users.filter((user) => {
return user.airplaneCompany == txtInp;
});
}, [txtInp]);
只需使用正則表達式。 只需放置輸入值,例如/^airplaneCompany$/
const wrongInputText = 'q' const rightInputText = 'airplaneCompany' console.log('wrong', 'return value=', /^airplaneCompany$/.test(wrongInputText)) console.log('right', 'return value=',/^airplaneCompany$/.test(rightInputText))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.