To determine whether a JSON object contains a specific key, you can use the hasOwnProperty()
method in JavaScript.
Here's an example:
const jsonObj = {
name: 'John',
age: 25,
city: 'New York'
};
if (jsonObj.hasOwnProperty('age')) {
console.log('JSON object has the key "age"');
} else {
console.log('JSON object does not have the key "age"');
}
In this example, we have a JSON object jsonObj
with three keys: name
, age
, and city
. We use the hasOwnProperty()
method to check if the object has the key 'age'
, and based on the result we log the appropriate message to the console.
Asked: 2022-10-04 11:00:00 +0000
Seen: 11 times
Last updated: Jun 22 '22