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>
<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!
Comments (0)