How to Check if a Value Exists in an Object in JavaScript
Table of Contents
Because JavaScript is a dynamically typed language, we can't sure of the type of an object.
Without knowing the object's type, it also means we don't know what properties or values it contains.
In this post, we'll learn how to check if a value exists inside an object in JavaScript.
How to check if a value exists in an object in JavaScript
Let's say we have an object like this:
JAVASCRIPTconst object = {
name: "John",
age: 30
};
We can check if a value exists in an object by first getting all of the values with Object.values()
and then using the includes()
method.
JAVASCRIPTconst object = {
name: "John",
age: 30
};
if (Object.values(object).includes("John")) {
console.log("Value exists");
} else {
console.log("Value does not exist");
}
BASHValue exists
You can tell it works because if we try using another name, it won't work:
JAVASCRIPTconst object = {
name: "John",
age: 30
};
if (Object.values(object).includes("Jane")) {
console.log("Value exists");
} else {
console.log("Value does not exist");
}
BASHValue does not exist
Alternatively, we can just iterate over the keys of an object and use the .some()
function to check if the value exists:
JAVASCRIPTconst object = {
name: "John",
age: 30
};
if (Object.keys(object).some((key) => object[key] === "John")) {
console.log("Value exists");
} else {
console.log("Value does not exist");
}
BASHValue exists
We can turn this into a reusable function:
JAVASCRIPTconst object = {
name: "John",
age: 30
};
const valueExists = (obj, value) => Object.keys(obj).some((key) => obj[key] === value);
if (valueExists(object, "John")) {
console.log("Value exists");
} else {
console.log("Value does not exist");
}
BASHValue exists
Conclusion
In this post, we learned how to check if a value exists in an object in JavaScript.
We can use the Object.values()
method to get all of the values in an object and then use the includes()
method to check if a value exists, or we can use the Object.keys()
method to get all of the keys in an object and then use the some()
method to check if a value exists.
Thanks for reading!
- Getting Started with Solid
- Managing PHP Dependencies with Composer
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Using Push.js to Display Web Browser Notifications
- Setting Up Stylus CSS Preprocessor
- Getting Started with Vuex: Managing State in Vue
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript