Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu March 15, 2023 › #HowTo #Javascript

Check if multiple key exists in JavaScript object

Are you trying to figure out how to check if multiple keys exist in an object using JavaScript? Well, look no further. In this blog post, I'll show you exactly how it can be done.

The first thing we need to do is create a sample object that contains two or more keys with values associated with them.

<script>
  const myObj = {
            name : 'Apu',
            age : 20, 
            country : 'India'
          };  
 // Sample Object containing 3 key-value pairs
</script>

Next up is creating an array of the keys that we want to check for inside of our example object (myObj).

<script>
  const myKeys = ['name', 'age'];   
</script>

Now all that’s left is writing some code which will iterate through each element within the ‘myKeys’ array and checks whether they exist as properties within the ‘myObject’ Object.

<script>
  let status = myKeys.every(key => key in myObj);   
</script>
The above example iterates over all elements from "myKeys" Array and compares it against properties inside "myObject". Returns true only when every single Key matches else returns false.
<script>
 const myObj = {
            name : 'Apu',
            age : 20, 
            country : 'India'
          };  
 const myKeys = ['name', 'age'];   
 let status = myKeys.every(key => key in myObj);   
 if (status){
   console.log('All keys do exist inside of our example object (myObj)')
 }else{
   console.log('All keys do not exist inside of our example object (myObj)')
 }
</script>

And there you have it! We now have a simple way for checking if multiple specific keys exists within any given JavaScript Objects!

save
listen
AI Answer
Write Your Answer
loading
back
View All