Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to check if key is exist in data or not

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

Returns true when key exists.

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

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading