Check if JSON property exist using JavaScript.
You need to check if a JSON property exists, before you use it. For, example,
let obj = {
keys: [1, 2, 3],
empInfo: {
firstName: 'jay',
lastName: 'raj',
age: 10
}
};
In the above JSON you can access firstName
as
obj.empInfo.firstName
But what if empInfo
doesn’t exist. You get an error. So, you need to check if empInfo
exists.
Using hasOwnProperty
You can do so using hasOwnProperty
.
let obj = {
keys: [1, 2, 3],
empInfo: {
firstName: 'jay',
lastName: 'raj',
age: 10
}
};
if(obj.hasOwnProperty('empInfo')){
console.log('first name is ', obj.empInfo.firstName)
}
// first name is jay
Using Optional Chaining
You can use a short hand for checking if JSON property exists using optional chaining (?.)
let obj = {
keys: [1, 2, 3],
empInfo: {
firstName: 'jay',
lastName: 'raj',
age: 10
}
};
console.log('first name is ', obj.empInfo?.firstName)
// first name is jay
If empInfo
doesn’t exist it returns undefined
.
Setting Default Using ??
You can also set a default value, in case,obj.empInfo?.firstName
returns undefined
using Nullish coalescing operator (??)
let obj = {
keys: [1, 2, 3],
empInfo: {
fName: 'jay',
lastName: 'raj',
age: 10
}
};
console.log(`first name ${obj.empInfo?.firstName ?? 'not found'}`)
// "first name not found"