Introduction
In this lab, we will explore how to check if an object has a specific value using JavaScript. We will learn how to use the Object.values() method to extract all the values of an object and how to use the Array.prototype.includes() method to check if a target value exists in the array of values. This knowledge will help us efficiently check for values in JSON objects in our JavaScript projects.
Function to Check if an Object Contains a Specific Value
To check if an object contains a specific value, use the following function:
const hasValue = (obj, value) => Object.values(obj).includes(value);
To use this function, pass in the object you want to search and the target value as arguments. The function will return true if the object contains the value and false if it does not.
Here's an example:
const obj = { a: 100, b: 200 };
console.log(hasValue(obj, 100)); // true
console.log(hasValue(obj, 999)); // false
To get started with coding, open the Terminal/SSH and type node.
Summary
Congratulations! You have completed the Check if Object Has Value lab. You can practice more labs in LabEx to improve your skills.