JavaScript | Check if a key exists inside a JSON object
Given a JSON Object, the task is to check whether a key exists in Object or not using JavaScript. We’re going to discuss few methods.
- hasOwnProperty()
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 return a boolean denoting if the object has the specified property as own property.
Example 1: This example checks for prop_1 of the obj by using hasOwnProperty property.
<!DOCTYPE HTML> < html > < head > < title > JavaScript | Check if a key exists inside a JSON object. </ title > </ head > < body style = "text-align:center;" id = "body" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style="font-size: 15px; font-weight: bold;"> </ p > < button onclick = "gfg_Run()" > check </ button > < p id = "GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var obj = { prop_1: "val_1", prop_2: "val_2", prop_3: "val_3", prop_4: "val_4", }; el_up.innerHTML = JSON.stringify(obj); function gfg_Run() { ans = ""; var prop = 'prop_1'; if (obj.hasOwnProperty(prop)) { ans = "var 'obj' has " + prop + " property"; } else { ans = "var 'obj' has not " + prop + " property"; } el_down.innerHTML = ans; } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button:
Example 2: This example checks for pro_1 of the obj by simple array access.
<!DOCTYPE HTML> < html > < head > < title > JavaScript | Check if a key exists inside a JSON object. </ title > </ head > < body style = "text-align:center;" id = "body" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style="font-size: 15px; font-weight: bold;"> </ p > < button onclick = "gfg_Run()" > check </ button > < p id = "GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var obj = { prop_1: "val_1", prop_2: "val_2", prop_3: "val_3", prop_4: "val_4", }; el_up.innerHTML = JSON.stringify(obj); function gfg_Run() { ans = ""; var prop = 'pro_1'; if (obj[prop]) { ans = "var 'obj' has " + prop + " property"; } else { ans = "var 'obj' has not " + prop + " property"; } el_down.innerHTML = ans; } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button: