Open In App
Related Articles

JavaScript Check if a key exists inside a JSON object

Improve Article
Improve
Save Article
Save
Like Article
Like

Given a JSON Object, the task is to check whether a key exists in the Object or not using JavaScript. We’re going to discuss a few methods.

JavaScript hasOwnProperty() Method: This 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)

Parameters:

  • prop: This parameter is required. It specifies the string name or Symbol of the property to check.

Return Value: It returns a boolean value indicating whether the object has the given property as its own property.

Example 1: This example checks for prop_1 of the obj by using hasOwnProperty property

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

Example 2: This example checks for pro_1 of the obj by simple array access. 

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 = 'pro_1';
    if (obj[prop]) {
        ans = "let 'obj' has " + prop + " property";
    } else {
        ans = "let 'obj' has not " + prop + " property";
    }
    console.log(ans);
}
gfg_Run()

Output

let 'obj' has not pro_1 property

Last Updated : 02 Jun, 2023
Like Article
Save Article
Similar Reads
Related Tutorials