0

Hi all I have following data of zip codes:

Now I am trying to do following. I have input and I am writing some zip code, I need to check if that zip code is exist in my data of zip codes I should set my state true if not exist then false.

here is my code:

const zipCode = {
  2101: [
    {
      City: "Boston",
      State: "Massachusetts",
      Delivery: "Yes",
      Address: ""
    }
  ],
  2108: [
    {
      City: "Boston",
      State: "Massachusetts",
      Delivery: "Yes",
      Address: ""
    }
  ],
  2109: [
    {
      City: "Boston",
      State: "Massachusetts",
      Delivery: "Yes",
      Address: ""
    }
  ],
  2110: [
    {
      City: "Boston",
      State: "Massachusetts",
      Delivery: "Yes",
      Address: ""
    }
  ],
  2111: [
    {
      City: "Boston",
      State: "Massachusetts",
      Delivery: "Yes",
      Address: ""
    }
  ],
  2112: [
    {
      City: "Boston",
      State: "Massachusetts",
      Delivery: "Yes",
      Address: ""
    }
  ],
  2113: [
    {
      City: "Boston",
      State: "Massachusetts",
      Delivery: "Yes",
      Address: ""
    }
  ],
 
};

export default zipCode;

    export default function App() {
     const [valid, setValid] = useState(null);
     const [zipCodefromInput, setZipCodeFromInput] = useState();

      const checkZipCode = (e) => {
       setZipCodeFromInput(+e.taget.value);

       Object.keys(zipCode)
        .filter((key) => zipCodefromInput.includes(key))
        .reduce((obj, key) => {
        obj[key] = zipCode[key];
        // setValid(true) else setValid(false) ???
       }, {});
     };

  console.log(valid);

  return (
    <div className="App">
      <input onChange={checkZipCode} />

     
    </div>
  );
}

But it not works for me, please help me to correct my code.

someone
  • 681
  • 4
  • 18

1 Answers1

2

Returns true when key exists.

const zipExists = (key) => key in zipCode;

More info: Checking if a key exists in a JavaScript object?

Bjop
  • 330
  • 4
  • 19