How to Check if Key is Present in JSON Object in Javascript

  • We have selected two elements button and h1 using the document.querySelector() method and stored them in btnCheck and result variables respectively.
  • We have a global variable jsonObj and it holds a JSON object.
  • We have attached the click event listener to the button element.
  • In the click event handler function, we are calling JSON.parse() method and passing our global variable jsonObj as a parameter. This method simply parses JSON object and returns a javascript object.  We assigned returned value to the obj variable.
  • We are using the hasOwnProperty() method to check if there is a property with a key name.
  • We are setting the inner text of the h1 element to the Boolean value returned by the hasOwnProperty() method.
let btnCheck = document.querySelector('button');
let result = document.querySelector('h1');

let jsonObj = '{"name":"Peter","age":"30"}';

btnCheck.addEventListener('click', () => {
    let obj = JSON.parse(jsonObj);
    result.innerText = obj.hasOwnProperty('name') ? 'True' : 'False';