Check if Object Has Value

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/ToolsandEnvironmentGroup(["`Tools and Environment`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") javascript/ToolsandEnvironmentGroup -.-> javascript/debugging("`Debugging`") subgraph Lab Skills javascript/variables -.-> lab-28521{{"`Check if Object Has Value`"}} javascript/data_types -.-> lab-28521{{"`Check if Object Has Value`"}} javascript/arith_ops -.-> lab-28521{{"`Check if Object Has Value`"}} javascript/comp_ops -.-> lab-28521{{"`Check if Object Has Value`"}} javascript/destr_assign -.-> lab-28521{{"`Check if Object Has Value`"}} javascript/debugging -.-> lab-28521{{"`Check if Object Has Value`"}} end

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.

Other JavaScript Tutorials you may like