Home > Net >  react on change check if equal to array of object
react on change check if equal to array of object

Time:07-09

i have input and array of object i need when i type it will display the object. "airplaneCompany" is the object property that i need to compare i was doing only if the input is equal to the "airplaneCompany" it will return it by the filter method but i need for evrey char it will check it and if the object start with "a" it will show this object

  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>
        );
      })}

CodePudding user response:

I think you can use your .filter function to check if the airplaneCompany starts with the user input?

Something like

return user.airplaneCompany.indexOf(txtInp) === 0;

CodePudding user response:

You can use @Patrick answer, but JavaScript has its own startsWith function you can use.

Also, consider wrapping the filter with the useMemo hook to run it only when the input changes and not on every render.

const showFlight = useMemo(() => {
  return users.filter((user) => {
    return user.airplaneCompany == txtInp;
  });
}, [txtInp]);

CodePudding user response:

just use regex. just place input value like /^airplaneCompany$/

const wrongInputText = 'q'
const rightInputText = 'airplaneCompany'

console.log('wrong', 'return value=', /^airplaneCompany$/.test(wrongInputText))

console.log('right', 'return value=',/^airplaneCompany$/.test(rightInputText))

  • Related