Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Check if JSON Key Value is Null in JavaScript ?
Next article icon

JavaScript Check if a key exists inside a JSON object

Last Updated : 10 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with JSON objects in JavaScript, it’s often necessary to check if a specific key exists within the object. This check is important, especially when dealing with dynamic or external data, to ensure that your code handles objects correctly and only accesses keys that are present.

Below are the methods to Check if a key exists inside a JSON object:

Methods to Check if a Key Exists Inside a JSON Object

Table of Content

  • Using hasOwnProperty() Method
  • Using in Operator
  • Using Object.getOwnPropertyNames() and includes() Method

Using hasOwnProperty() Method

JavaScript hasOwnProperty() Method returns a boolean denoting whether the object has the defined property as its own property (as opposed to inheriting it).

Syntax:

obj.hasOwnProperty(prop);

Example: In this example the gfg_Run, the function checks if obj has its own property prop_1 using hasOwnProperty(). It logs that obj has this property because it exists.

JavaScript
let obj = {     prop_1: "val_1",     prop_2: "val_2",     prop_3: "val_3",     prop_4: "val_4", }; function gfg_Run() {     ans = "";     let prop = 'prop_1';     if (obj.hasOwnProperty(prop)) {         ans = "let 'obj' has " + prop + " property";     } else {         ans = "let 'obj' has not " + prop + " property";     }     console.log(ans); } gfg_Run() 

Output
let 'obj' has prop_1 property 


Using in Operator

JavaScript in Operator is an inbuilt operator which is used to check whether a particular property exists in an object or not. It returns a boolean value true if the specified property is in an object, otherwise, it returns false.

Syntax

prop in object

Example: In this example, The in operator checks if a specified key, like age, exists in the jsonObject. It returns true if the key exists, otherwise false.

JavaScript
// Example JSON object let jsonObject = {     name: 'John',     age: 25,     city: 'New York' };  // Check if 'age' key exists in jsonObject if ('age' in jsonObject) {     console.log('The key "age" exists in the JSON object.'); } else {     console.log('The key "age" does not exist in the JSON object.'); } 

Output
The key "age" exists in the JSON object. 

Using Object.getOwnPropertyNames() and includes() Method

The Object.getOwnPropertyNames() method in JavaScript is a standard built-in object which returns all properties that are present in a given object except for those symbol-based non-enumerable properties.

Syntax

Object.getOwnPropertyNames(obj);

Example: In this example, the Object.getOwnPropertyNames() returns an array of property names from jsonObject. includes(keyToCheck) checks if keyToCheck is in that array, confirming its presence in the object.

JavaScript
const jsonObject = {   key1: 'value1',   key2: 'value2',   key3: 'value3' };  const keyToCheck = 'key2';  if (Object.getOwnPropertyNames(jsonObject).includes(keyToCheck)) {   console.log(`${keyToCheck} exists in the JSON object.`); } else {   console.log(`${keyToCheck} does not exist in the JSON object.`); } 

Output
key2 exists in the JSON object. 


Next Article
How to Check if JSON Key Value is Null in JavaScript ?

P

PranchalKatiyar
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions
  • JSON

Similar Reads

  • How to Check a Key Exists in JavaScript Object?
    Here are different ways to check a key exists in an object in JavaScript. Note: Objects in JavaScript are non-primitive data types that hold an unordered collection of key-value pairs. 1. Using in Operator The in operator in JavaScript checks if a key exists in an object by returning a boolean value
    2 min read
  • How to Check if Object is JSON in JavaScript ?
    JSON is used to store and exchange data in a structured format. To check if an object is JSON in JavaScript, you can use various approaches and methods. There are several possible approaches to check if the object is JSON in JavaScript which are as follows: Table of Content Using Constructor Type Ch
    3 min read
  • Check if a Set is Empty in JavaScript?
    These are the following ways to check whether the given set is empty or not: 1. Using size property - Mostly usedThe size property is used to get the size of the set. if it returns 0 then the set will be empty else it has some elements. [GFGTABS] JavaScript let s = new Set(); if (s.size === 0) conso
    2 min read
  • Javascript - Catching error if json key does not exist
    In this article, we will discuss the error handling when a key is not present inside the javascript object. A JSON is a string format that encloses a javascript object in double-quotes.  Example: '{"site": "gfg"}' A JSON object literal is the javascript object present inside the JSON String.  Exampl
    2 min read
  • How to Check if JSON Key Value is Null in JavaScript ?
    In JavaScript, the JSON Object can contain null values, which should be identified. The below approaches can be used to check if the JSON key is null. Table of Content Using for Loop and '===' OperatorUsing Object.values() with Array.prototype.includes()Using Array.prototype.some()Using for Loop and
    3 min read
  • How to check if a value is object-like in JavaScript ?
    In JavaScript, objects are a collection of related data. It is also a container for name-value pairs. In JavaScript, we can check the type of value in many ways. Basically, we check if a value is object-like using typeof, instanceof, constructor, and Object.prototype.toString.call(k). All of the ope
    4 min read
  • How to check whether an object exists in javascript ?
    Checking whether an object exists in JavaScript refers to determining if a variable or property has been declared and contains a valid value. This helps avoid errors when accessing or manipulating objects that may be undefined, null, or not initialized properly. Here we have some common approaches t
    3 min read
  • Deserializing a JSON into a JavaScript object
    Deserializing a JSON into a JavaScript object refers to the process of converting a JSON (JavaScript Object Notation) formatted string into a native JavaScript object. This allows developers to work with the data in JavaScript by accessing its properties and methods directly. JavaScript Object Notat
    2 min read
  • How to Check if the Response of a Fetch is a JSON Object in JavaScript?
    In JavaScript, when making HTTP requests using the Fetch API, it's common to expect JSON data as a response from the server. However, before working with the response data, it's essential to verify whether it is indeed a JSON object or not. The below approaches can help you to check if the response
    2 min read
  • How to check if an array includes an object in JavaScript ?
    Check if an array includes an object in JavaScript, which refers to determining whether a specific object is present within an array. Since objects are compared by reference, various methods are used to identify if an object with matching properties exists in the array. These are the following appro
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences